Technique to make a canvas drawLine() clickable?

2019-01-29 04:38发布

I'm working on an app that plots nodes on a map, and each node has edges that are represented by a line between them. I've drawn the edges using Canvas and drawLine(), but it would be useful if the lines themselves could be clickable. By that I mean a method of allowing the user to touch the line or think they're touching the line and an event can trigger. (like display edge info, etc...)

I can't rightly attach a touch event to a line I've drawn with Canvas, so I was thinking of placing ImageViews inbetween the ends of each edge line that's drawn. The ImageView could be a dot so it's clear where the touch event triggers.

Does anyone have any other suggestions? I'm mainly looking for ideas that I've missed. Maybe there's something in the Android API that can help with this that I'm unaware of.

Thanks in advance for any tips!

1条回答
祖国的老花朵
2楼-- · 2019-01-29 04:53

Use a path to draw the line:

Path linePath;
Paint p;
RectF rectF;
float point1X, point1Y, point2X, point2Y;

// initialize components

// draw the line
linePath.moveTo(point1X, point1Y); 
linePath.lineTo(point2X, point2Y);

canvas.drawPath(linePath, p);

linePath.computeBounds(rectF, true);

Override onTouchEvent(MotionEvent):

@Override
public boolean onTouchEvent(MotionEvent event) {

    float touchX = event.getX();
    float touchY = event.getY();

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        if (rectF.contains(touchX, touchY)) {
            // line has been clicked
        }
        break;
    }
    return true;
}
查看更多
登录 后发表回答