2013-11-04 65 views
1

我目前正在尝试使用电影在自定义视图中显示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,这是不对的? 有什么想法?

+0

由于您的GIF是一种资源,可以考虑使用我的'gif2animdraw'脚本到GIF转换成'AnimationDrawable'和一系列的帧:https://gist.github.com/commonsguy/6757059 – CommonsWare

+0

有趣的,但我使用这个drawable只是为了测试。最后,我希望能够显示从网络请求中检索到的GIF –

+0

哦,是的,我的脚本无法帮助这种情况,对不起。 – CommonsWare

回答

0

如果您需要在Android中正确播放GIF,我想您应该使用第三个库,因为该框架本身不支持该格式。一对夫妇的项目,你可能会感兴趣的是

  • ImageViewEx:Android的的ImageView的扩展,支持GIF动画,包括更好的密度管理

  • ION:Android的异步网络变得容易。获得了GIF支持few days ago,并且明确适用于下载和显示远程GIF。

+0

感谢您的回答。上面的代码使用与第一个库相同的方法。第二个库使用Java gif解码器。我昨天试了一下,第二种方式正在工作。我要实现我自己的方式,因为这两个库只是为了我的需要矫枉过正。无论如何,感谢您的评论。 –

相关问题