在按钮背景上设置 GIF

Set GIF on Background of button

是否可以在 button.I 的背景上应用 GIF 已尝试通过以下代码参考 this。我的代码在下面。

   public class GIFView extends View {
    Movie movie, movie1;
    InputStream is = null, is1 = null;
    long moviestart;

    public GIFView(Context context) {
        super(context);
        is = context.getResources().openRawResource(+R.drawable.cloudinary_animation);// avoid error ( “Expected resource of type raw”)by +
        movie = Movie.decodeStream(is);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawColor(Color.WHITE);
        super.onDraw(canvas);
        long now = android.os.SystemClock.uptimeMillis();
        System.out.println("now=" + now);
        if (moviestart == 0) { // first time
            moviestart = now;

        }
        System.out.println("\tmoviestart=" + moviestart);
        int relTime = (int) ((now - moviestart) % movie.duration());
        System.out.println("time=" + relTime + "\treltime=" + movie.duration());
        movie.setTime(relTime);
        movie.draw(canvas, this.getWidth() / 2 - 20, this.getHeight() / 2 - 40);
        this.invalidate();
    }
}

现在我想在按钮的背景上应用这个动画。

I have implemented this in my application a day ago.Although this tutorial is >about ImageView you can easily convert the code to your advantage.

首先,这取决于你的愿望。

1: Repeatedly continue to play the Gif (It is easy)

2: Play only once similar to Facebook app "Like" button (Some work is required)


将此库添加到您的 gradle.build

编译'pl.droidsonroids.gif:android-gif-drawable:1.2.8'


GifImageView gifImageView;

GifDrawable gifDrawable;

定义这个变量:

gifImageView = findViewById(R.id.splashGif);

<pl.droidsonroids.gif.GifImageView
        android:id="@+id/splashGif"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#FFFDFF"
        />


播放GIF

 public void playGif() {


        try {
            gifDrawable = new GifDrawable(getActivity().getResources(), R.drawable.SplashGifId);
        } catch (IOException e) {
            e.printStackTrace();
        }


        gifDrawable.setLoopCount(1);

        gifDrawable.addAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationCompleted(int loopNumber) {

                gifImageView.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.SplashLastFrame));

            }
        });

        gifImageView.setImageDrawable(gifDrawable);



}

This method will play the gif R.drawable.SplashGifId after finishing process of GIF you will set the last frame (R.drawable.SplashLastFrame) of GIF to your button or ImageView.

要拆分您的 gif 并获取 gif 的最后一帧,您可以使用此在线工具:

https://ezgif.com/split


使用此资源并通知我...干杯!