Technique to make a canvas drawLine() clickable?

佐手、 提交于 2019-12-18 09:23:08

问题


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:


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;
}


来源:https://stackoverflow.com/questions/18275032/technique-to-make-a-canvas-drawline-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!