我想通过在Android Studio中绘制画布来做一个简单的动画。我按照本教程系列设置了基本的java代码(参见下面的代码):
https://www.youtube.com/watch?v=UH2OWnq7NQ4
他正在覆盖run()方法以完成所有绘图,但是其他人似乎都在onDraw()方法中执行此操作。哪种方法一般更好?这样做会不会遇到问题?
public class AnimationActivity extends SurfaceView implements Runnable {
Thread thread = null;
boolean canDraw = false;
Bitmap backgroundBlack;
Canvas canvas;
SurfaceHolder surfaceHolder;
public AnimationActivity(Context context) {
super(context);
surfaceHolder = getHolder();
backgroundBlack = BitmapFactory.decodeResource(getResources(), R.drawable.background_black);
}
@Override
public void run() {
prepPaintBrushes();
while (canDraw) {
if (!surfaceHolder.getSurface().isValid()) {
continue;
}
canvas = surfaceHolder.lockCanvas();
canvas.drawBitmap(backgroundBlack,0,0, null);
//drawing is done here
surfaceHolder.unlockCanvasAndPost(canvas);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void pause() {
canDraw = false;
while (true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
thread = null;
}
public void resume() {
canDraw = true;
thread = new Thread(this);
thread.start();
}
}
答案 0 :(得分:0)
我不熟悉这个特殊的API,但根据我在图形编程方面的经验,编写自己的渲染循环对我来说似乎非常可疑。拨打sleep()
也是一个很大的禁忌。这两种情况都会导致用户界面反应迟钝。
我建议您阅读the official Android site上SurfaceView
的文档和教程。