思路:
通过View.setOnTouchListener()
提供的Api获取到手指触摸屏幕的坐标,然后通过Canvas.drawLine()
在 bitmap 上画出手指经过的路径。
建议先参阅 Android开发:对图片进行简单的编辑。
第一步:
- 向 drawable 文件夹中添加一个背景图,以作画板背景。假设文件名为
bg.jpg
。 - 往布局文件中添加一个
ImageView
以作画板。假设其 id 为:iv_pad
。
第二步:
声明这些成员变量
private ImageView iv_pad; //画板
private int startX,startY;//手指触摸起始位置
//用于绘制路径
private Canvas canvas;
private Paint paint;
private Bitmap bmp;//用于编辑的 Bitmap .
在onCreate()
方法中将上文声明的变量实例化。
iv_pad = (ImageView) findViewById(R.id.iv_pad);
paint = new Paint();
//不理解的话请先看思路中提到的参阅博客
Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.background);
bmp = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
canvas = new Canvas(bmCopy);
canvas.drawBitmap(bmSrc, new Matrix(), paint);//此时的 bmp 就是背景图。
第三步:
实现 ImageView
的触摸监听。
iv_pad.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) event.getX();
startY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX();
int y = (int) event.getY();
canvas.drawLine(startX, startY, x, y, paint);
startX = x;
startY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
pad.setImageBitmap(bmp);//在触摸的过程中将 bmp 显示到画板上,达到不断刷新的效果。
return true;
}
});
第四步
运行。
添加修改画笔颜色、宽度及保存图片的功能。
- 修改画笔颜色:
paint.setColor(int color);
- 修改画笔宽度:
paint.setStrokeWidth(float width);
保存图片到sd卡:
//不要忘了申请权限。 public void save() throws IOException{ File file = new File("sdcard/myPaint.png"); FileOutputStream fos = new FileOutputStream(file); //对 Bitmap 进行压缩,中间的 100 为质量,从 0 到 100 图片质量由低到高。 bmCopy.compress(CompressFormat.PNG, 100, fos); fos.close(); }