Think Different

GIFView 만들기 본문

OS/Android

GIFView 만들기

TENNESSEE 2014. 9. 22. 03:51

안드로이드에서 기본으로 제공하는 기본 View들은 GIF 이미지 재생을 지원하지 않는다. 그래서 GIF 이미지 재생을 원하는 사용자는 View를 상속받아 커스터마이징하여 직접 구현해야 한다.


Problem

  • GIF 이미지를 지원하는 View가 없음


Solution

  • View를 상속받아 커스터마이징을 하여 구현


Example

package sehoonkim.android.view;

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

public class GIFView extends View {
	private Movie movie = null;
	private long movieStart = 0;
	
	
	public GIFView(Context context) {
		super(context);
	}
	
	public GIFView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public GIFView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	public void setResource(Movie movie) {
		this.movie = movie;
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (this.movie != null) {
			setMeasuredDimension(this.movie.width(), this.movie.height());
		} else {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.TRANSPARENT);
		super.onDraw(canvas);
		
		long now = SystemClock.uptimeMillis();
		int duration = 0;
		int relayTime = 0;
		
		if (this.movieStart == 0) {
			this.movieStart = now;
		}
		
		if (this.movie != null) {
			duration = this.movie.duration();
			
			if (duration == 0) {
				duration = 5000;
			}
			
			relayTime = (int)((now - this.movieStart) % duration);
			this.movie.setTime(relayTime);
			
			float scaleWidth = (float)((getWidth() / (1f * this.movie.width())));
			float scaleHeight = (float)((getHeight() / (1f * this.movie.height())));
			
			canvas.scale(scaleWidth, scaleHeight);
			
			this.movie.draw(canvas, 0, 0);
			
			this.invalidate();
		}
		
	}
	
}


Usage - Java

package sehoonkim.android.view;

import android.app.Activity;
import android.view.View;
import sehoonkim.android.view.GIFView;


public abstract class GIFViewTest implements Activity {
	private GIFView gifView = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gifViewTest);
		
		this.gifView = (GIFView)findVIewById(R.id.gifView_gifImage);
	}
}


Usage - XML



	
	
	


Reference

  • http://droid-blog.net/2011/10/14/tutorial-how-to-use-animated-gifs-in-android-part-1/
  • http://droid-blog.net/2011/10/14/tutorial-how-to-use-animated-gifs-in-android-part-2/
  • http://droid-blog.net/2011/10/14/tutorial-how-to-use-animated-gifs-in-android-part-3/
  • http://stackoverflow.com/questions/6533942/adding-gif-image-in-an-imageview-in-android
  • http://abhinavasblog.blogspot.kr/2014/04/animated-gif-imageview-library-for.html
  • http://weavora.com/blog/2012/02/07/android-and-how-to-use-animated-gifs/