Lar*_*erg 6 animation android canvas opengl-es
我有30多个单位图(320x240像素),我想在Android设备上一个接一个地全屏显示,从而产生一个动画.目前,我使用ImageView和Timer实现动画,设置下一帧,然后发送将应用下一帧的消息.得到的帧速率非常低:<2 fps.
计时器:
animationTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Drawable frame = getNextFrame();
if (frame != null) {
Message message = animationFrameHandler.obtainMessage(1, frame);
animationFrameHandler.sendMessage(message);
}
}
}, 0, (int) (1000.0d / fps));
Run Code Online (Sandbox Code Playgroud)
处理程序:
final Handler animationFrameHandler = new Handler() {
@Override
public void handleMessage(Message message) {
setImageDrawable((Drawable) message.obj);
}
};
Run Code Online (Sandbox Code Playgroud)
由于我想要实现高达30 fps的帧速率,我必须使用另一种机制并听说Canvas.drawBitmapMesh()和OpenGL.
如果可能的话我想避免使用OpenGL.
非常感谢您分享您的经验!
我现在的工作方法如下:
在开始动画之前,将每个帧加载到一个List<Bitmap>
.重要提示:System.gc()
如果您正在使用OutOfMemoryError
s,请调用- 这确实有助于将更多位图加载到内存中.然后运行一个线程,将下一帧发布到View实例,然后更新它的画布.
加载帧并开始动画
// Loading the frames before starting the animation
List<Bitmap> frames = new ArrayList<Bitmap>();
for (int i = 0; i < 30; i++) {
// Load next frame (e. g. from drawable or assets folder)
frames.add(...);
// Do garbage collection every 3rd frame; really helps loading all frames into memory
if (i %% 3 == 0) {
System.gc();
}
}
// Start animation
frameIndex = 0;
animationThread.start();
Run Code Online (Sandbox Code Playgroud)
应用下一帧的线程
private final class AnimationThread extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
// Post next frame to be displayed
animationView.postFrame(frames.get(frameIndex));
// Apply next frame (restart if last frame has reached)
frameIndex++;
if (frameIndex >= frames.size()) {
frameIndex = 0;
}
try {
sleep(33); // delay between frames in msec (33 msec mean 30 fps)
} catch (InterruptedException e) {
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
动画视图
class AnimationView extends View {
Bitmap frame = null;
public void postFrame(Bitmap frame) {
Message message = frameHandler.obtainMessage(0, frame);
frameHandler.sendMessage(message);
}
protected final Handler frameHandler = new Handler() {
@Override
public void handleMessage(Message message) {
if (message.obj != null) {
frame = (Bitmap) message.obj;
} else {
frame = null;
}
invalidate();
}
}
@Override
protected void onDraw(Canvas canvas) {
if (frame == null) return;
canvas.drawARGB(0, 0, 0, 0);
canvas.drawBitmap(frame, null, null, null);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7215 次 |
最近记录: |