我正在尝试将图像加载到SurfaceView,并在此图像上绘制一些划痕。
为此,我创建了一个自定义SurfaceView,MySurfaceView,具有以下功能:
public MySurfaceView(Context context, AttributeSet attrs)
{
super(context, attrs);
mHolder = getHolder();
mHolder.addCallback(this);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(3);
mPaint.setColor(Color.WHITE);
setWillNotDraw(false);
}
public void setImageBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mBitmap, x, y, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mPath = new Path();
mPath.moveTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mPath.lineTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mPath.lineTo(event.getX(), event.getY());
}
if (mPath != null) {
Canvas canvas = mHolder.lockCanvas();
canvas.drawPath(mPath, mPaint);
mHolder.unlockCanvasAndPost(canvas);
}
return true;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
基本上如果在构造函数中保留 setWillNotDraw(false),SurfaceView将显示我设置 mBitmap 的位图。否则,如果我对此进行评论,它将允许我在黑色背景上绘制路径。
我有什么方法可以做到这两点,将图像(mBitmap)放在后台并在此图像上绘制路径?你们能提供一些代码吗?非常感谢!
答案 0 :(得分:1)
我明白了。
基本上将绘制路径放到 onDraw(Canvas canvas)函数中。为了确保在绘制路径后,SurfaceView调用onDraw。我们需要在触摸事件中调用 invalidate()。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmapScaled, x, y, null);
if (mPath != null) {
canvas.drawPath(mPath, mPaint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mPath = new Path();
mPath.moveTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mPath.lineTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mPath.lineTo(event.getX(), event.getY());
}
invalidate();
return true;
}
甚至更好,您可以将mPath更改为ArrayList,以便在图像上放置更多路径。