使用Glide V4 实现GIF点赞动画

序言

最近的项目中,客户提出一个点赞动画。给了一个gif图。如下

这里写图片描述

最终的效果是这样的。

这里写图片描述

这其中也有一些知识点分享给大家:

  1. 怎么动态的添加一个动画到指定的View
  2. 怎么实现GIF只播放一次
  3. 这么监听GIF播放完毕的时间(因为需要在结束时播放消失动画)

实现

我的思路是通过需要显示的View的getLocationInWindow 方法,拿到其相对于屏幕的坐标。然后拿到Activity 的最外层布局。即decorView。由于decorView 基本上是FrameLayout。这样就可以动态的添加一个ImageView用于显示动画。而GIF的播放我使用的是Glide V4.0 。网上有许多V3.0 播放GIF的方法。但是4.0 的还比较少。在获取GIF时长的方法中由于4.0中GifDecoder 没有提供API直接从GifDrawable 中获取。所以使用了反射的方式获取。最重要的代码我封装到了LikeUtil中。

package com.zgh.likedemo.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.zgh.likedemo.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by zhuguohui on 2018/6/13.
 */

public class LikeUtil {

    /**
     * 显示点赞动画
     *
     * @param locationView 需要定位的view,动画将显示在其左下方
     * @param xOffset      x轴的偏移量
     * @param yOffset      y轴的偏移量
     */
    public static void showLike(View locationView, int xOffset, int yOffset) {
        if (locationView == null) {
            return;
        }
        Context context = locationView.getContext();
        if (!(context instanceof Activity)) {
            return;
        }
        //1.获取Activity最外层的DecorView
        Activity activity = (Activity) context;
        View decorView = activity.getWindow().getDecorView();
        FrameLayout frameLayout = null;
        if (decorView != null && decorView instanceof FrameLayout) {
            frameLayout = (FrameLayout) decorView;
        }
        if (frameLayout == null) {
            return;
        }
        //2.通过getLocationInWindow 获取需要显示的位置
        ImageView likeView = new ImageView(context);
        //注意不能使用warp_content 在实际的代码运行中。高度会比GIF的高度高。因此这里直接使用GIF的大小作为ImageView的大小
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(172, 219);
        int[] outLocation = new int[2];
        locationView.getLocationInWindow(outLocation);
        // 80 和 100 是一点点测试出来的。不同的需求可以自己测出需要的偏移量
        layoutParams.leftMargin = outLocation[0] + xOffset - 80;
        layoutParams.topMargin = outLocation[1] + yOffset - 100;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        likeView.setLayoutParams(layoutParams);
        frameLayout.addView(likeView);
        
        //3.创建消失动画
        Animation dismissAnimation = new AlphaAnimation(1.0f, 0.0f);
        dismissAnimation.setDuration(500);
        dismissAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ViewGroup parent = (ViewGroup) likeView.getParent();
                if (parent != null) {
                    parent.removeView(likeView);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        
        //4.监听GIF消失事件
        loadOneTimeGif(context, R.drawable.ic_like_flower, likeView, new GifListener() {
            @Override
            public void gifPlayComplete() {
                likeView.post(() -> {
                    int[] location = new int[2];
                    likeView.getLocationOnScreen(location);

                    likeView.startAnimation(dismissAnimation);
                });
            }
        });


    }

    
    @SuppressLint("CheckResult")
    public static void loadOneTimeGif(Context context, Object model, final ImageView imageView, final GifListener gifListener) {
        RequestOptions option = new RequestOptions();
        //关闭缓存,在连续播放多个相同的Gif时,会出现第二个Gif是从最后一帧开始播放的。
        option.diskCacheStrategy(DiskCacheStrategy.NONE);
        option.skipMemoryCache(true);
        Glide.with(context).asGif().load(model).apply(option).listener(new RequestListener<GifDrawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                try {
                    Field gifStateField = GifDrawable.class.getDeclaredField("state");
                    gifStateField.setAccessible(true);
                    Class gifStateClass = Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable$GifState");
                    Field gifFrameLoaderField = gifStateClass.getDeclaredField("frameLoader");
                    gifFrameLoaderField.setAccessible(true);
                    Class gifFrameLoaderClass = Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader");
                    Field gifDecoderField = gifFrameLoaderClass.getDeclaredField("gifDecoder");
                    gifDecoderField.setAccessible(true);
                    Class gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder");
                    Object gifDecoder = gifDecoderField.get(gifFrameLoaderField.get(gifStateField.get(resource)));
                    Method getDelayMethod = gifDecoderClass.getDeclaredMethod("getDelay", int.class);
                    getDelayMethod.setAccessible(true);
                    //设置只播放一次
                    resource.setLoopCount(1);
                    //获得总帧数
                    int count = resource.getFrameCount();
                    int delay = 0;
                    for (int i = 0; i < count; i++) {
                        //计算每一帧所需要的时间进行累加
                        delay += (int) getDelayMethod.invoke(gifDecoder, i);
                    }
                    imageView.postDelayed(() -> {
                        if (gifListener != null) {
                            gifListener.gifPlayComplete();
                        }
                    }, delay);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        }).into(imageView);
    }

    /**
     * Gif播放完毕回调
     */
    public interface GifListener {
        void gifPlayComplete();
    }
}

使用起来也很简单。

  tv_like.setOnClickListener(v -> {
            boolean newLikeState = !data.get(i).isLiked();
            tv_like.setSelected(newLikeState);
            data.get(i).setLiked(newLikeState);
            if (newLikeState) {
                LikeUtil.showLike( tv_like, 0, 0);
            }
        });

源码

有兴趣的可以下载看一下
使用Glide4.0 实现点赞动画的demo

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,062评论 25 707
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,960评论 3 119
  • 岁月极美 在于它必然流逝 春花,秋月,夏日,冬雪 ------三毛
    NXde水蔓青阅读 296评论 0 0
  • 中国有名的亭台楼阁,要说是因为一首序,而名扬天下的,当属滕王阁!序是人写的,所以说,滕王阁的名扬天下是因为...
    499275893d98阅读 914评论 6 4
  • 奕23阅读 212评论 0 1