首页 > 解决方案 > 路径上的 onTouchEvent

问题描述

我发现它的宽度RectF是 0.0,所以这就是为什么它总是错误的。那么我可以设置RectFStrokeWidth的宽度吗?

我有一条路。我想处理点击它。所以我发现我可以通过 onTouchEvent 进行检查。

因此,在OnDraw()方法中,我绘制了一条路径并将边界添加到rectF我猜想left, right, top, bottom的正确位置。onTouchEvent


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class PathTest extends View {

    Paint paint;
    Path path;
    RectF rectF = new RectF();

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        path.moveTo((float)getWidth()/2,getHeight()-20);
        path.lineTo((float)getWidth()/2,20);
        path.close();
        path.computeBounds(rectF,true);

        canvas.drawPath(path,paint);


    }

    private void init(){
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(100);
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        path = new Path();




    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(width,height/2);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN){
            if(rectF.contains(event.getX(),event.getY())){
                Log.d("HALLO","HI");
            }else{
                Log.d("HALLO","left"+rectF.left+" top"+rectF.top+" right"+rectF.right+" bottom"+rectF.bottom + " x->"+event.getX()+" y->"+event.getY());
            }
        }


        return super.onTouchEvent(event);
    }
}

在此处输入图像描述 它总是其他的。我不知道为什么。

所以我记录rectF坐标和MotionEvent.ACTION_DOWN事件。

D/HALLO: left540.0 top20.0 right540.0 bottom2240.0 x->528.0 y->490.0
D/HALLO: left540.0 top20.0 right540.0 bottom2240.0 x->1047.0 y->1021.0
D/HALLO: left540.0 top20.0 right540.0 bottom2240.0 x->1016.0 y->961.0
D/HALLO: left540.0 top20.0 right540.0 bottom2240.0 x->1059.0 y->1062.0```




标签: androidandroid-custom-viewtouch-event

解决方案


推荐阅读