public class BAGraffitiView extends View { private int panitColor; private Bitmap mBitmap; private float downX, downY; private float tempX, tempY; private Bitmap src; private ListdrawPathList; private Paint paint; private Path path; private Bitmap resultBitmap; public BAGraffitiView(Context context) { super(context); } public BAGraffitiView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public BAGraffitiView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } private void init() { drawPathList = new ArrayList<>(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mBitmap != null) { if (src == null) { int width = canvas.getWidth(); int height = canvas.getHeight(); int bWidth = mBitmap.getWidth(); int bHeight = mBitmap.getHeight(); float wScale = (float) width/bWidth; float hScale = (float) height/bHeight; Matrix matrix = new Matrix(); matrix.postScale(wScale, hScale); src = Bitmap.createBitmap(mBitmap, 0, 0, bWidth, bHeight, matrix, true); } canvas.drawBitmap(src, 0, 0, null); } if (drawPathList != null && drawPathList.size() != 0) { for (DrawPath drawPath : drawPathList) { canvas.drawPath(drawPath.path, drawPath.paint); } } canvas.save(); } private void initValue() { paint = new Paint(); path = new Path(); paint.setAntiAlias(true); paint.setStrokeWidth(10); paint.setStyle(Paint.Style.STROKE); if (panitColor == 0) { paint.setColor(Color.RED); } else { paint.setColor(panitColor); } } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: initValue(); downX = event.getX(); downY = event.getY(); path.moveTo(downX, downY); invalidate(); tempX = downX; tempY = downY; DrawPath drawPath = new DrawPath(); drawPath.paint = paint; drawPath.path = path; drawPathList.add(drawPath); break; case MotionEvent.ACTION_MOVE: float moveX = event.getX(); float moveY = event.getY(); path.quadTo(tempX, tempY, moveX, moveY); invalidate(); tempX = moveX; tempY = moveY; break; } return true; } //设置颜色 public void setPanitColor(int panitColor) { this.panitColor = panitColor; } //设置背景图片 public void setmBitmap(Bitmap mBitmap) { this.mBitmap = mBitmap; } //撤销 public void undo() { if (drawPathList.size() > 0) { drawPathList.remove(drawPathList.size() - 1); invalidate(); } } public Bitmap getSrc() { return this.src; } class DrawPath { Paint paint; Path path; }}