在Android中绘制和擦除触摸可以通过使用Canvas和Paint类来实现。下面是一个简单的示例代码:
public class DrawingView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mPaint;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
public DrawingView(Context context) {
super(context);
init();
}
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(5);
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
canvas.drawPath(mPath, mPaint);
}
private void touchStart(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touchMove(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touchUp() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
invalidate();
break;
}
return true;
}
public void clearCanvas() {
mCanvas.drawColor(Color.WHITE);
invalidate();
}
}
这个示例代码创建了一个自定义的View,用于绘制和擦除触摸。在onDraw方法中,首先绘制了之前绘制的内容(mBitmap),然后绘制当前的路径(mPath)。在onTouchEvent方法中,根据触摸事件的不同动作,调用相应的方法来处理绘制和擦除的逻辑。
要在Android中使用这个自定义View,可以在布局文件中添加以下代码:
<com.example.app.DrawingView
android:id="@+id/drawing_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后在Activity中获取该View的实例,并设置相应的监听器:
DrawingView drawingView = findViewById(R.id.drawing_view);
drawingView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// 处理触摸事件
return true;
}
});
这样就可以在Android中实现绘制和擦除触摸的功能了。
推荐的腾讯云相关产品:无
请注意,由于要求不能提及具体的云计算品牌商,因此无法提供腾讯云相关产品和产品介绍链接地址。
领取专属 10元无门槛券
手把手带您无忧上云