Detecting touch inside a irregular shape in ImageView

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?

Answers


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

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.


Need Your Help

How to implement semi-randomized level in iPhone game?

ios

I want to create a game with a level structure similar to iCopter or Canabalt, where each level has a randomized floor (and roof), but the height of the floor is never impossible to reach from the

symfony2: inserting data using eventListener

symfony doctrine-orm symfony-2.3

I'm using symfony 2.3. I'm trying to generate an Invoice for every commercial every end of a month. I implemented a Listener called InvoiceListener in order to that. The problem is updateInvoice()