[英]How can I animate a bitmap's opacity using Canvas in Android?
I'm fairly new to Android programming. 我是Android编程的新手。 I'm trying to create an animation of a bitmap image using Canvas
in Android. 我正在尝试使用Android中的Canvas
创建位图图像的动画。 I am using setAlpha()
to manipulate the opacity of the bitmap. 我使用setAlpha()
来操纵位图的不透明度。 My drawFrame()
method includes the following bit: 我的drawFrame()
方法包括以下内容:
c = holder.lockCanvas();
drawScene(c, paint);
holder.unlockCanvasAndPost(c);
My drawScene()
includes this bit: 我的drawScene()
包括这个位:
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. 我想我必须插入一个循环来修改0到255之间的paint
并退回。 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
. 编辑 :这是我的Runnable
代码。 paint
is a private double
set to 255. boom_activated
is a boolean
that becomes true
if the onTouchEvent
enabled it. paint
是一个private double
设置为255. boom_activated
是一个boolean
,如果onTouchEvent
启用它,它将变为true
。 It should stay true
until the Runnable
disables it ( setBoomState(false);
). 它应该保持为true
直到Runnable
禁用它( 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: 在我的drawScene()
我有这一行:
scene_handler.postDelayed(DrawSceneThread, 25);
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. 另外,我建议将您的Paint实例和绘制变量从drawScene中取出并在全局范围内声明它,以便您可以重用它。 It would hurt performance when recreating it over and over. 一遍又一遍地重建它会损害性能。
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. 您需要使用处理程序更新alpha值,然后在onDraw函数中绘制位图。 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 看看本教程,以便更好地了解通过处理程序更新UI: http : //developer.android.com/resources/articles/timed-ui-updates.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.