画画板小案例
Posted nangongyibin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了画画板小案例相关的知识,希望对你有一定的参考价值。
画画板小案例
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Paint paint; private Bitmap bitmapC; @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button changC = findViewById(R.id.changeColor); changC.setOnClickListener(this); Button bold = findViewById(R.id.bold); bold.setOnClickListener(this); Button save = findViewById(R.id.save); save.setOnClickListener(this); final ImageView iv = findViewById(R.id.iv); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg); bitmapC = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); paint = new Paint(); final Canvas canvas = new Canvas(bitmapC); canvas.drawBitmap(bitmap, new Matrix(), paint); iv.setImageBitmap(bitmapC); iv.setOnTouchListener(new View.OnTouchListener() { float startX = 0; float startY = 0; @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: startX = event.getX(); startY = event.getY(); break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE: float stopX = event.getX(); float stopY = event.getY(); canvas.drawLine(startX, startY, stopX, stopY, paint); iv.setImageBitmap(bitmapC); startX = stopX; startY = stopY; break; } return true; } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.changeColor: paint.setColor(Color.RED); break; case R.id.bold: paint.setStrokeWidth(20f); break; case R.id.save: try { File file = new File(getFilesDir().getParent(), "dazuo.png"); FileOutputStream fos = new FileOutputStream(file); boolean compress = bitmapC.compress(Bitmap.CompressFormat.PNG, 100, fos); if (compress) { Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException e) { Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } break; } } }
代码已上传https://gitee.com/nangongyibin/android_DrawingVersion
以上是关于画画板小案例的主要内容,如果未能解决你的问题,请参考以下文章