使用Canvas制作可点击的位图

时间:2011-05-25 07:30:27

标签: android canvas clickable

希望这是完成我的应用程序的最后一步。我需要在一个可点击的画布中制作一个位图,它将调用一个播放视频的新活动(mp4)或在当前活动中播放视频。

显示画布和位图的类是我反复使用的类,用于显示缩略图的完整图像。图像ID通过Intent传递。这是完整图像活动的代码(我非常喜欢使用这个网站和其他人一步一步拼凑我的代码,所以如果它不干净我就道歉):

public class full_image extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(new BitmapView(this));
    getWindow().setBackgroundDrawableResource(R.drawable.bground);
    getWindow().setWindowAnimations(0);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                           WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

class BitmapView extends View {
    public BitmapView(Context context) {
        super(context);
    }

    @Override
    public void onDraw(Canvas canvas) {
        int imgid = getIntent().getIntExtra("Full",0);
        Bitmap fullimage = BitmapFactory.decodeResource(getResources(),imgid);
        Bitmap playButton = BitmapFactory.decodeResource(getResources(), R.drawable.bt_play); //Added for Video
        Display display = getWindowManager().getDefaultDisplay();
        int fpWidth = fullimage.getWidth();
        int fpHeight = fullimage.getHeight();
        int playWidth = playButton.getWidth(); 
        int playHeight = playButton.getHeight(); 
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();
        int leftPoint = screenWidth/2 - fpWidth/2;
        int topPoint = screenHeight/2 - fpHeight/2;
        int leftPlayPoint = screenWidth/2 - playWidth/2; 
        int topPlayPoint = screenHeight/2 - playHeight/2; 
        canvas.drawBitmap(fullimage,leftPoint,topPoint,null);
        canvas.drawBitmap(playButton,leftPlayPoint,topPlayPoint,null); 

    }
}  
}

如果可能的话,我希望只有playButton来容纳onClickListener,但如果它更容易,我可以使整个画布可点击(如果可能的话)。

我读到另一个问题,其中有建议使用TouchEvent。我试过去那条路但却无法上班。这是正确的道路,我只需要更多地使用它来使其发挥作用吗?

谢谢,J

其他材料:

这是我在另一个问题中找到的一段代码。我将把这段代码放在上面提供的代码中。

public boolean onTouchEvent(MotionEvent event){
int action = event.getAction();
int x = event.getX()  // or getRawX();
int y = event.getY();

switch(action){
case MotionEvent.ACTION_DOWN:
    if (x >= xOfYourBitmap && x < (xOfYourBitmap + yourBitmap.getWidth())
            && y >= yOfYourBitmap && y < (yOfYourBitmap + yourBitmap.getHeight())) {
        //tada, if this is true, you've started your click inside your bitmap
    }
    break;
}

}

1 个答案:

答案 0 :(得分:5)

我认为我们无法在canvas中设置onOnClick位图。 但我们可以使用onTouch方法。并检查触摸位图或不使用x-y触摸位置。

在onTouch方法中尝试此代码以获取位图...

if (x >= xOfYourBitmap && x < (xOfYourBitmap + yourBitmap.getWidth())
                && y >= yOfYourBitmap && y < (yOfYourBitmap + yourBitmap.getHeight())) {
            //tada, if this is true, you've started your click inside your bitmap
        }