Detecting Touch Inside A Irregular Shape In Imageview
Solution 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.
publicclassFooBarextendsImageView {
Bitmapb=null;
publicFooBar(Context context) {
super(context);
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
super.onDraw(canvas);
b = getDrawingCache(true);
}
@OverridepublicbooleanonTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE)
check((int) event.getX(), (int) event.getY());
returnsuper.onTouchEvent(event);
}
privatevoidcheck(int x, int y) {
if (b != null && Color.alpha(b.getPixel(x, y)) >= 0)
onMovedOutOfShape();
}
privatevoidonMovedOutOfShape() {
Toast.makeText(getContext(), "You're out", Toast.LENGTH_SHORT).show();
}
}
Solution 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.
Post a Comment for "Detecting Touch Inside A Irregular Shape In Imageview"