3

I'm fairly new to Android programming. I'm trying to create an animation of a bitmap image using Canvas in Android. I am using setAlpha() to manipulate the opacity of the bitmap. My drawFrame() method includes the following bit:

c = holder.lockCanvas();  
drawScene(c, paint);  
holder.unlockCanvasAndPost(c); 

My drawScene() includes this bit:

Paint transparencyValue = new Paint();  
transparencyValue.setAlpha(paint);
canvas.drawBitmap(boom.getImage(), logoToBoom.getX(), logoToBoom.getY(),
    transparencyValue);

I imagine I have to insert a loop to modify paint from 0 to 255 and back down. So far it hasn't worked, but I am probably doing something wrong. Could anyone please recommend something?

EDIT: Here is my code for the Runnable. paint is a private double set to 255. boom_activated is a boolean that becomes true if the onTouchEvent enabled it. It should stay true until the Runnable disables it (setBoomState(false);). For some reason it's still not drawing the bitmap at the decreasing opacity. Is the code below valid, or am I missing something?

    private final Runnable DrawSceneThread = new Runnable() {
        public void run() {
            if (boom_activated && paint <= 0) {
                paint = 0;
                drawFrame();
                setBoomState(false);
                paint = 255;
            } else if (boom_activated && paint >= 0) {
                drawFrame();
                paint -= 0.7;
            } else {
                drawFrame();
            }`

In my drawScene() I have this line:
scene_handler.postDelayed(DrawSceneThread, 25);

Daniel Gray
  • 1,697
  • 1
  • 21
  • 41
NVtool
  • 77
  • 1
  • 6

2 Answers2

0

Refer to this topic How to change a bitmap's opacity?

Also, I would recommend to take your Paint instance and paint variable out of your drawScene and declare it in a global scope so you can reuse it. It would hurt performance when recreating it over and over.

Community
  • 1
  • 1
Will Kru
  • 5,164
  • 3
  • 28
  • 41
  • I am using Canvas. Would the line below properly display the paint as declared in my original post, as opposed to what I use right now? canvas.drawBitmap(bitmap, src, dst, paint); – NVtool Mar 23 '11 at 04:04
0

What you have to do is to animate the opacity values over time. You need to use a handler to update the alpha values and then draw the bitmap in your onDraw function. Have a look at this tutorial to get a better idea about updating the UI through handlers: http://developer.android.com/resources/articles/timed-ui-updates.html

Abhinav
  • 38,516
  • 9
  • 41
  • 49
  • Can't post code very well in comments :( Refer to main post for the edit ^ – NVtool Mar 23 '11 at 03:33
  • You don't need to call drawFrame() yourself. Just invalidate the view and onDraw will be called automatically. Are you overriding onDraw in your view? – Abhinav Mar 23 '11 at 07:43