主函数
public class MainActivity extends AppCompatActivity {
ImageView iv;
Paint paint;
Canvas canvas;
Bitmap copyBimap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chenwei);
copyBimap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
paint = new Paint();
canvas = new Canvas(copyBimap);
canvas.drawBitmap(bitmap, new Matrix(), paint);
//改变画笔的颜色
paint.setColor(Color.RED);
//改变画笔的大小
paint.setStrokeWidth(5);
iv.setImageBitmap(copyBimap);
//图片的保存
try{
File file = new File(getExternalCacheDir(), "text.png");
FileOutputStream fos = new FileOutputStream(file);
copyBimap.compress(Bitmap.CompressFormat.PNG,100,fos);}
catch (Exception e){
e.printStackTrace();
}
iv.setOnTouchListener(new View.OnTouchListener() {
int startX;
int startY;
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN://按下屏幕
//获取按下屏幕的位置
startX = (int) event.getX();
startY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE://移动
//d当前手指的位置
int endX = (int) event.getX();
int endy = (int) event.getY();
System.out.println(startX + " " + startY + " " + endX + " " + endy);
//划线
canvas.drawLine(startX, startY, endX, endy, paint);
iv.setImageBitmap(copyBimap);
//更新初始位置
startX = endX;
startY = endy;
break;
case MotionEvent.ACTION_UP://离开屏幕
iv.setImageBitmap(copyBimap);
break;
}
//一定要该为true
return true;
}
});
}
}