2015-12-11 107 views
2

我正在使用下面的类。如何根据点击事件停止并开始循环?我试着删除invalidate(),但Gif并没有开始加载。如何在Android中停止gif动画?

GifView类

import java.io.InputStream; 

import com.example.merchant.R; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Movie; 
import android.os.SystemClock; 
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 movieStart; 

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.ani_bart); 

    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 = SystemClock.uptimeMillis(); 

    if(movieStart == 0) { 
     movieStart = now; 
    } 

    if(gifMovie != null) { 

     int dur = gifMovie.duration(); 
     if(dur == 0) { 
      dur = 1000; 
     } 

     int relTime = (int)((now - movieStart) % dur); 

     gifMovie.setTime(relTime); 

     gifMovie.draw(canvas, 0, 0); 
     invalidate(); 
    } 
} 

}

+0

一个'boolean'字段添加到类 - 例如,'私人布尔IsPlaying模块;' - 检查的第一件事就是'的onDraw()'和'返回;'如果是'FALSE'。创建公共方法来启动和停止,在每个方法中适当地设置字段,然后在启动方法结束时调用'invalidate()'。 –

+0

当我想结束动画时,你能告诉我停止方法中应该使用的代码吗? – Anirudh

+0

'isPlaying = false;' –

回答

1

来控制行走,你可以在Android的创造FRME aniation这是我用什么克服这个问题。但是,如果这是一个有效的解决方案,不太确定。尽管为我工作。

@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; 
     } 
     now = android.os.SystemClock.uptimeMillis(); 
     int relTime = (int) ((now - mMovieStart) % dur); 
     if (now - mMovieStart > movieDuration) { 
      relTime = 0; 
     } 

     gifMovie.setTime(relTime); 

     gifMovie.draw(canvas, 0, 0); 
     invalidate(); 

    } 
}