开发者

How can I animate a bitmap's opacity using Canvas in Android?

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);开发者_如何学Go


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜