安卓为你打造gifView轻松播动画

本文详细介绍了如何在Android应用中使用GIF图片,并通过代码示例展示了GIF图片的播放与管理。主要涉及到GIFView的创建、初始化、以及如何实现GIF的循环播放。

很久没有写东西了,手有点生疏了,项目中有可能用到gif图片的话,直接拿去用就好了,懒得多说自己去看效果

 

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
>

  <com.example.csa.GifView
    android:id="@+id/iv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="20dp" />

</RelativeLayout>

MyGifView.class

package com.example.csa;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;

public class GifView extends View {
 
  //表示开始播放gif图片的绝对时间
  private long movieStart = 0;
  //movie对象管理gif图片里面的多个帧
  private Movie movie;

  public GifView(Context context, AttributeSet attrs) {
    super(context, attrs);
    movie = Movie.decodeStream(context.getResources().openRawResource(
         R.raw.media_gif));
  }

  @Override
  protected void onDraw(Canvas canvas) {
    long currentTime = System.currentTimeMillis();
    // 第一次播放
    if (movieStart == 0) {
      movieStart = currentTime;
    }
   
    //循环播放
    if (movie != null) {
      int duration = movie.duration();
      int relTime = (int) ((currentTime - movieStart) % duration);
      movie.setTime(relTime);
      movie.draw(canvas, 0, 0);
      // 强制重绘
      invalidate();
    }
   
    //如果只想播放一次,只需判断currentTime-movieStart的值大于duration就不重绘即可

    super.onDraw(canvas);
  }
}


public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }

 
}

值得注意的是manifest.xml


如果targetSdkVersion>13的时候gif不能在正常显示效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值