Skip to content

Instantly share code, notes, and snippets.

@Tobiaqs
Created May 5, 2014 23:38
Show Gist options
  • Save Tobiaqs/1eeec8e6eef449cb5d21 to your computer and use it in GitHub Desktop.
Save Tobiaqs/1eeec8e6eef449cb5d21 to your computer and use it in GitHub Desktop.
package tobiass.statedebt.view;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidParameterException;
import tobiass.statedebt.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;
public class GifView extends View {
Movie movie;
long moviestart;
public GifView(Context context) {
super(context);
}
public GifView(Context context, AttributeSet set) throws IOException {
super(context, set);
TypedArray a = context.getTheme().obtainStyledAttributes(set, R.styleable.GifView, 0, 0);
int res = a.getResourceId(R.styleable.GifView_drawable, -1);
String asset = a.getString(R.styleable.GifView_asset);
a.recycle();
if(asset != null) {
loadGIFAsset(asset);
}
else if(res > -1) {
loadGIFResource(res);
}
else {
throw new InvalidParameterException();
}
}
public void loadGIFResource(int id) {
InputStream is = getContext().getResources().openRawResource(id);
movie = Movie.decodeStream(is);
invalidate();
}
public void loadGIFAsset(String filename) throws IOException {
InputStream is;
try {
is = getContext().getResources().getAssets().open(filename);
movie = Movie.decodeStream(is);
invalidate();
} catch (IOException e) {
throw e;
}
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(movie != null) {
long now = android.os.SystemClock.uptimeMillis();
if (moviestart == 0)
moviestart = now;
movie.setTime((int) ((now - moviestart) % movie.duration()));
movie.draw(canvas, 0, 0);
invalidate();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment