我的目标是创建一个自定义视图,其中将位图设置为背景。用户可以在其上突出显示/绘制线条。我可以通过从View扩展一个类并重写onDraw方法来实现此目的。但是问题是如何获得相对于位图的触摸坐标?我想保存这些坐标并将其上传到云中,以便可以在其他设备上重画线。我不想将画布转换为位图,然后保存。 这是当前的代码,只画线-
public class HighlightView extends View {
private Path drawPath;
private Paint canvasPaint;
private Paint drawPaint;
private int paintColor = 0x660000;
private Canvas drawCanvas;
private Bitmap canvasBitmap;
private float currentBrushSize;
private ArrayList<Path> paths = new ArrayList<>();
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void init() {
currentBrushSize = 50;
drawPath = new Path();
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(currentBrushSize);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
drawPaint.setAlpha(100);
canvasPaint = new Paint(Paint.DITHER_FLAG);
}
public HighlightView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
protected void onDraw(Canvas canvas) {
for (Path p : paths) {
canvas.drawPath(p, drawPaint);
}
canvas.drawPath(drawPath, drawPaint);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float touchX = event.getX();
float touchY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(touchX, touchY);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(touchX, touchY);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
default:
return false;
}
return true;
}
private void touch_start(float x, float y) {
drawPath.reset();
drawPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_up() {
drawPath.lineTo(mX, mY);
drawCanvas.drawPath(drawPath, drawPaint);
paths.add(drawPath);
drawPath = new Path();
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
drawPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
public void onClickUndo() {
if (paths.size() > 0) {
paths.remove(paths.size() - 1);
invalidate();
}
}
public void onClickClearAll() {
if (paths.size()>0){
paths.clear();
invalidate();
}
}
}