1.加载背景图
Bitmap bmSrc = BitmapFactory.decodeResource(图片资源); 2.创建图片副本
bmCopy=Bitmap.createBitmap(bmSrc.getWidth(),bmSrc.getHeight(),bmSrc.getConfig()); 3.创建画笔
paint = new Paint(); 4.创建画板
canvas=new Canvas(bmCopy); 5.进行绘制
canvas.drawBitmap(bmSrc,new Matrix(),paint); iv.setImageBitmap(bmCopy); 6.设置触摸监听,绘制出划过的轨迹
源码(+图片的保存)
public class MainActivity extends AppCompatActivity { private ImageView iv; private int startX; private int startY; private Canvas canvas; private Bitmap bmCopy; private Paint paint; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.iv); //加载画板背景图 Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.mipmap.iv); //创建副本,纸 bmCopy=Bitmap.createBitmap(bmSrc.getWidth(),bmSrc.getHeight(),bmSrc.getConfig()); //笔 paint = new Paint(); //画板 canvas=new Canvas(bmCopy); //绘制 canvas.drawBitmap(bmSrc,new Matrix(),paint); iv.setImageBitmap(bmCopy); //设置触摸监听 iv.setOnTouchListener(new View.OnTouchListener() { //触摸屏幕时,触摸时间产生时,此方法被调用 @Override public boolean onTouch(View view, MotionEvent motionEvent) { int action = motionEvent.getAction(); switch (action) { //用户手指触摸到屏幕 case MotionEvent.ACTION_DOWN: // Log.i("ACTION", "onTouch: " + "触摸屏幕"); startX= (int) motionEvent.getX(); startY= (int) motionEvent.getY(); break; //用户手指在屏幕上滑动 case MotionEvent.ACTION_MOVE: int x = (int) motionEvent.getX(); int y = (int) motionEvent.getY(); canvas.drawLine(startX,startY,x,y,paint); iv.setImageBitmap(bmCopy); //把每次绘制的结束坐标变为下次的开始坐标 startX=x; startY=y; Log.i("ACTION", "onTouch: " + "滑动屏幕"); break; //用户手指离开屏幕 case MotionEvent.ACTION_UP: Log.i("ACTION", "onTouch: " + "离开屏幕"); break; } //true:告诉系统这个触摸事件有我来处理 //false:告诉系统我不处理这个事件,这时系统会把这个触摸事件传递给该View的父节点 return true; } }); } /** * 图片的保存,并及时在图库中显示 * */ public void save(View view){ File file=new File(Environment.getExternalStorageDirectory(),"dauzo.png"); FileOutputStream fos= null; try { fos = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } bmCopy.compress(Bitmap.CompressFormat.PNG,100,fos); //发送SD卡就绪广播,让系统把保存的图片显示到图库中 Intent intent=new Intent(); intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(file)); sendBroadcast(intent); }