如何使用画布上设置位图图像onTouchEvent。 [英] How to set onTouchEvent on Bitmap image using canvas.
问题描述
我是在android开发新的。我想特别是对于图像设置onTouchEvent。这样我可以做一些工作,比如增加分数等...
i'm new in android development. I wanted to set onTouchEvent particularly for an image. so that i can do some work ,like increase score etc....
下面是示例code我尝试..
Here is the sample code i tried..
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawBitmap(image1, random.nextInt(455), random.nextInt(270), paint);
canvas.drawText("SCORE = "+score, 10, 20, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
if(toggelFlag)
{
score = score+10;
}
return super.onTouchEvent(event);
}
其实我想增加得分一次我只触碰图像。但在这里,如果我的任何地方轻触屏幕的增加得分。我希望它仅用于图像。
Actually i wanted to increase the score once i touch the image only. But here if i touch anywhere in the screen its increase the score. I want it for image only.
推荐答案
创建与图像边界这样的区域对象:
Create a Region object with the image bounds like this:
Region region = new Region(left, top, right, bottom);
左,上,右,下定义图像范围。
left, top, right and bottom define the image bounds.
然后,当你处理触摸事件检查,如果区域包含事件的位置。将是:
Then, when you handle a touch event check if region contains the event position. Would be:
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY();
if(region.contains((int)x, (int)y))
{
// touch in image
}
return super.onTouchEvent(event);
}
这篇关于如何使用画布上设置位图图像onTouchEvent。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!