zoukankan      html  css  js  c++  java
  • Android显示GIF图片

    今天我们研究一下怎样在Android手机上显示GIF动态图片
    首先须要在src文件夹下新建一个自己定义的View。代码例如以下:

    </pre><pre name="code" class="java">
    </pre><pre name="code" class="java">

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Movie;
    import android.util.AttributeSet;
    import android.view.View;
    
    public class MyGifView extends View {
    	
    	//表示開始播放gif图片的绝对时间
    	private long movieStart = 0;
    	//movie对象管理gif图片里面的多个帧
    	private Movie movie;
    
    	public MyGifView(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		movie = Movie.decodeStream(context.getResources().openRawResource(
    				R.drawable.horse));
    	}
    
    	@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);
    	}
    }

    接着写一个Activity,用来显示gif图片:

    import android.app.Activity;
    import android.os.Bundle;
    
    public class MainActivity extends Activity {
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_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"
        tools:context="${relativePackage}.${activityClass}" >
    
        <com.example.gifdemo.MyGifView
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp" />
    
    </RelativeLayout>

    效果图例如以下:



    整个演示样例project文件下载链接:

    Android显示GIF图片


  • 相关阅读:
    Codeforces Round #324 (Div. 2) D. Dima and Lisa 哥德巴赫猜想
    Codeforces Round #324 (Div. 2) C. Marina and Vasya 贪心
    Codeforces Round #324 (Div. 2) B. Kolya and Tanya 快速幂
    Codeforces Round #324 (Div. 2) A. Olesya and Rodion 水题
    使用spring-loaded实现应用热部署
    maven中properties标签定义变量
    java中的匿名内部类总结
    泛型类型限定和通配符类型限定
    基于ActiveMQ的Topic的数据同步——消费者持久化
    基于ActiveMQ的Topic的数据同步——初步实现
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5181398.html
Copyright © 2011-2022 走看看