Detecting touch inside a irregular shape in ImageView

二次信任 提交于 2020-01-06 13:12:34

问题


I have an ImageView which has a transparent drawable with a circle at the center like (http://wallpaperswide.com/circle_outline-wallpapers.html). Just that the circle is red, and the surrounding are not coloured but are transparent, it is a .png image. So now I will implement Canvas.ondraw(), and when while tracing the user goes outside the circle, the drawing should restart.

The doubt is: 1. How do I detect the boundaries of this image without hardcoding. 2. How do I detect that the user has clicked outside this, as this is not a regular rectangle.

I am doing this to help students trace alphabets, so I want the answer to be generic on the basis of any image in the shape of a letter. Can it be done this way? If not, what better way can you suggest?


回答1:


i'd go the easy route: just draw the image and check the colour of the point the user touched. if the alpha channel transparent, the user moved out.

the following code is untested (and very rough). i have no idea if the getDrawingCache trick works.

public class FooBar extends ImageView {

Bitmap b = null;

public FooBar(Context context) {
    super(context);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    b = getDrawingCache(true);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_MOVE)
        check((int) event.getX(), (int) event.getY());

    return super.onTouchEvent(event);
}

private void check(int x, int y) {
    if (b != null && Color.alpha(b.getPixel(x, y)) >= 0)
        onMovedOutOfShape();
}

private void onMovedOutOfShape() {
    Toast.makeText(getContext(), "You're out", Toast.LENGTH_SHORT).show();
}
}



回答2:


What you're after is almost the same thing as "collision detection for irregular shapes". Googling on that will result in a zillion hits.

But if I had the problem to do, I'd probably bring in one of the game engines/frameworks such as Box2D, AndEngine, libGDX, or BatteryTech. I'd combine a few simple rectangles and curves to build up reactive places over each of my letter images and then use of of the library's pre-optimized collision detection algorithms to do the heavy lifting. I'd also at least look through their open source code to learn how they do their detection.



来源:https://stackoverflow.com/questions/22300877/detecting-touch-inside-a-irregular-shape-in-imageview

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