我一直坚持将gif添加到ImageView中。 我明白使用WebView可以轻松地反复显示gif,但有没有办法在ImageView中添加gif? 我尝试将WebView转换为ImageView使用以下代码:
image = new ImageView(context);
view = new GifWebView(context, "file:///android_asset/move.gif");
Bitmap bmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
Canvas c= new Canvas(bmap);
view.draw(c);
image.setMaxHeight(500);
image.setMaxWidth(500);
image.setImageBitmap(bmap);
image.setVisibility(View.VISIBLE);
但是当我运行它时,只有500 * 500的白色空间。
答案 0 :(得分:1)
import java.io.InputStream;
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 {
private InputStream gifInputStream;
private Movie gifMovie;
private int movieWidth, movieHeight;
private long movieDuration;
private long mMovieStart;
public Gifview(Context context) {
super(context);
init(context);
}
public Gifview(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public Gifview(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context){
setFocusable(true);
gifInputStream = context.getResources()
.openRawResource(R.drawable.skiing);
gifMovie = Movie.decodeStream(gifInputStream);
movieWidth = gifMovie.width();
movieHeight = gifMovie.height();
movieDuration = gifMovie.duration();
}
@Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
setMeasuredDimension(movieWidth, movieHeight);
}
public int getMovieWidth(){
return movieWidth;
}
public int getMovieHeight(){
return movieHeight;
}
public long getMovieDuration(){
return movieDuration;
}
@Override
protected void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (gifMovie != null) {
int dur = gifMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int)((now - mMovieStart) % dur);
gifMovie.setTime(relTime);
gifMovie.draw(canvas, 0, 0);
invalidate();
}
}
}
使用此视图。放置你的gif图像而不是滑雪。
这是我的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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.playgif.MainActivity" >
<com.example.playgif.Gifview
android:id="@+id/gifview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>