我目前正在尝试使用电影在自定义视图中显示gif图像。我从字面上最常用的方式做到这一点:为什么我的gif图像没有动画效果?
public class GifView extends View {
private Movie movie;
private long timeElapsed;
public GifView(Context context) {
super(context);
init();
}
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GifView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
timeElapsed = 0;
setImage(getResources().openRawResource(R.drawable.sample));
}
public void setImage(byte[] bytes) {
movie = Movie.decodeByteArray(bytes, 0, bytes.length);
invalidate();
}
public void setImage(InputStream is) {
movie = Movie.decodeStream(is);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
super.onDraw(canvas);
long now = android.os.SystemClock.uptimeMillis();
if (timeElapsed == 0) { // first time
timeElapsed = now;
}
if (movie != null) {
int dur = movie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - timeElapsed) % dur);
movie.setTime(relTime);
movie.draw(canvas, getWidth() - movie.width(), getHeight() - movie.height());
invalidate();
}
}
}
这是我的电话(的Nexus 4运行API 18)上仅显示GIF的第一帧。 我读过,禁用此视图的hardwareAcceleration是必需的,以使其显示(没有显示,如果我删除相关行)。 我试过用其他的gif图片,并得到了相同的结果。 我注意到的一件事是movie.getDuration()
总是返回0,这是不对的? 有什么想法?
由于您的GIF是一种资源,可以考虑使用我的'gif2animdraw'脚本到GIF转换成'AnimationDrawable'和一系列的帧:https://gist.github.com/commonsguy/6757059 – CommonsWare
有趣的,但我使用这个drawable只是为了测试。最后,我希望能够显示从网络请求中检索到的GIF –
哦,是的,我的脚本无法帮助这种情况,对不起。 – CommonsWare