温馨提示×

android drawcircle怎样处理触摸事件

小樊
81
2024-12-08 17:25:26
栏目: 编程语言

在Android中,要在自定义View上处理触摸事件并绘制圆形,你需要重写onTouchEvent方法来处理触摸事件,并在onDraw方法中使用CanvasdrawCircle方法来绘制圆形。以下是一个简单的示例:

  1. 首先,创建一个名为CustomCircleView的自定义View类:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.appcompat.widget.AppCompatView;

public class CustomCircleView extends AppCompatView {

    private Paint paint;
    private RectF circleRect;
    private float touchX, touchY;

    public CustomCircleView(Context context) {
        super(context);
        init();
    }

    public CustomCircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        circleRect = new RectF();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(touchX, touchY, 50, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchX = event.getX();
                touchY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                touchX = event.getX();
                touchY = event.getY();
                invalidate(); // 重绘视图
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }
}
  1. 然后,在布局文件中使用这个自定义View:
<your.package.name.CustomCircleView
    android:id="@+id/custom_circle_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

现在,当你在CustomCircleView上触摸时,它将绘制一个圆形,并根据触摸位置更新圆的位置。

0