Reputation: 207
My Question is how can I move a bitmap on a canvas?
Recently I'm making a game and There's a button.
When I'm clicking on this button I want to move the bitmap (Only X) but when i'm doing this the bitmap is gone.
Here's the code :
"main_right" is the button that I'm clicking on. I also tried to put "invalidate()" there but it also didn't work.
@Override
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (x > width - main_right.getWidth()
&& x < width - main_right.getWidth()
+ main_right.getWidth()
&& y > height
- (main_right.getHeight() + main_right.getHeight() / 2)
&& y < height
- (main_right.getHeight() + main_right.getHeight() / 2)
+ main_right.getHeight()) {
x += 1;
canvas_main.drawBitmap(image, (width / 2) + x2,
height - (image.getHeight() + image.getHeight() / 2),
paint);
} else {
x = 0;
}
return true;
}
return false;
}
Upvotes: 1
Views: 1002
Reputation: 2950
canvas_main.drawBitmap(image, (width / 2) + x,
height - (image.getHeight() + image.getHeight() / 2),
paint);
The height might be the problem if your bitmap is > (device height/3)
height - (image.getHeight() + image.getHeight() / 2)
In essence means height - 1.5*image height. Since the top left of the bitmap is placed at that coordinate, the image will disappear out of the screen.
It should be
height - (image.getHeight() - image.getHeight() / 2)
or
height - image.getHeight() / 2
Upvotes: 0
Reputation: 18276
Store the x position on your onTouchEvent and draw at your canvas inside the onDraw(Canvas), that is the surface you need to draw.
Upvotes: 2