我试图在画布中循环图像(扩展视图类)来创建一个动画(就像一个GIF一样)但是它一直滞后和口吃我的应用......
例如:
public PlayView(Context context) {
super(context);
loadFrames();
this.context = context;
}
protected void onDraw(final Canvas canvas) {
canvas_main = canvas;
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted())
try {
Thread.sleep(10);
time = (time + 1) % 4;
image = images[time];
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
invalidate();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
if (image != null) {
System.out.println("Image is not null!");
if (!right_Clicked) {
canvas_main.drawBitmap(image, width / 2,
height - (image.getHeight() + image.getHeight() / 2),
paint);
}
super.onDraw(canvas_main);
}
void loadFrames() {
res = getResources();
images[0] = BitmapFactory.decodeResource(res, R.drawable.image_1);
images[1] = BitmapFactory.decodeResource(res, R.drawable.image_2);
images[2] = BitmapFactory.decodeResource(res, R.drawable.image_3);
images[3] = BitmapFactory.decodeResource(res, R.drawable.image_4);
}
如何设置循环图像以便创建没有滞后和口吃的动画?
答案 0 :(得分:0)
这是你可以做到的一种方式。离开活动时杀死线程是个好主意。
Thread mAnimationThread;
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Not needed canvas_main = canvas;
if (mAnimationThread == null) {
mAnimationThread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted())
try {
Thread.sleep(10);
time = (time + 1) % 4;
image = images[time];
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
invalidate();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
mAnimationThread.start();
}
if (image != null) {
if (!right_Clicked) {
canvas.drawBitmap(image, width / 2,
height - (image.getHeight() + image.getHeight() / 2),
paint);
}
}
}