高仿QQ視頻加點炫酷特效—你這樣玩過嗎

提及APP呢,每一個人都有那麼幾款喜歡的而且常用的應用,我呢喜歡的應用有這麼幾個:QQ、酷狗、今日頭條、百度貼吧等等。不只僅是由於我常用它們,更重要的是我做爲一名移動開發者認爲它們作的很好,裏面的一些效果常常會吸引我,它們會常常創新,使用戶體驗更好~好了,廢話很少說(廣告也不打了,他們老總又不給我錢)。說到QQ,前不久更新了一版其中的登陸界面的背景再也不是單調的一張圖片了而是一個有不少漂亮妹子的視頻在播放,說實話我看到的時候還挺耳目一新的,由於以前沒見到過這樣的APP,最多也就加個動畫,好吧又扯了一大堆,來看看效果圖吧!java

Paste_Image.png
Paste_Image.png

既然都說了那麼多了,不妨在多寫一點,雷軍曾經說過要作米粉心中最酷的公司,我本人呢也是一個忠實的米粉。雖然騰訊不是我心中最酷的公司,可是他們家的應用QQ我仍是很喜歡的,由於功能強大優化很好,就拿剛纔的登陸頁面來講我就以爲很漂亮,(注意:切入正題~)最後我就想若是再在界面上加一些滿天飛的彩色氣泡那不就美炸了,哈哈哈,因而就無聊寫着完了,順便鞏固一下屬性動畫的知識,再來放個效果圖(git圖太大,因此截的比較短)~,這裏加個小的友情提示:下載一個QQ的APK包,把擴展名改爲.zip格式而後解壓出來就能找到視頻圖片表情等這些個資源文件了哦,通常人我不告訴他~android

Paste_Image.png
Paste_Image.png

好吧,又扯了這麼多,下面該上點真東西了~照例先放個GitHub傳送門:BalloonRelativeLayout
看到這樣的一個效果,該如何去實現呢?有人就要說了,這TM不就是相似直播間點贊效果的實現嗎?yeah,You are right ! ! ! 我只不過把點贊換成了氣泡(機智如我)git

整體思路和原理

1.自定義ViewGroup繼承自RelativeLayout;
2.在自定義ViewGroup裏添加一個個的view(氣泡);
3.使view(氣泡)沿着貝塞爾曲線的軌跡移動;複製代碼

好的,整體大體思路就是這麼多吧,更細節的東西繼續往下看:github

1.自定義ViewGroup繼承自RelativeLayout:

這次咱們主要是實現功能,不考慮太多的擴展性,就不自定義屬性啦~數組

public class BalloonRelativeLayout extends RelativeLayout {

    public BalloonRelativeLayout(Context context) {
        this(context, null);
    }

    public BalloonRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BalloonRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    //重寫測量方法,獲取寬高
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
    }複製代碼

接下來把目光指向咱們的氣泡君~
[1].先來加工一下咱們的氣泡view:這裏我選擇了三張不一樣的圖片獲取Drawable對象而後放到drawables數組裏面備用;bash

private Drawable[] drawables;

//初始化顯示的圖片
drawables = new Drawable[3];
Drawable mBalloon = ContextCompat.getDrawable(mContext, R.mipmap.balloon_pink);
Drawable mBalloon2 = ContextCompat.getDrawable(mContext, R.mipmap.balloon_purple);
Drawable mBalloon3 = ContextCompat.getDrawable(mContext, R.mipmap.balloon_blue);
drawables[0] = mBalloon;
drawables[1] = mBalloon2;
drawables[2] = mBalloon3;複製代碼

[2].既然有氣泡了,那麼就得對氣泡進行一些處理微信

private int mViewHeight = dip2px(getContext(), 50);//默認50dp
private LayoutParams layoutParams;

//設置view寬高相等,默認都是50dp
layoutParams = new LayoutParams(mViewHeight, mViewHeight);
layoutParams.addRule(ALIGN_PARENT_BOTTOM, TRUE);複製代碼

[3].爲了讓氣泡的動畫顯得更天然和隨機性,那麼咱們還須要兩個東西,屬性動畫中的插值器Interpolator和隨機數Random;app

private Interpolator[] interpolators;//插值器數組
private Interpolator linearInterpolator = new LinearInterpolator();// 以常量速率改變
private Interpolator accelerateInterpolator = new AccelerateInterpolator();//加速
private Interpolator decelerateInterpolator = new DecelerateInterpolator();//減速
private Interpolator accelerateDecelerateInterpolator = new AccelerateDecelerateInterpolator();//先加速後減速

// 初始化插值器
interpolators = new Interpolator[4];
interpolators[0] = linearInterpolator;
interpolators[1] = accelerateInterpolator;
interpolators[2] = decelerateInterpolator;
interpolators[3] = accelerateDecelerateInterpolator;複製代碼

2.在自定義ViewGroup裏添加一個個的view(氣泡);

OK,氣泡已經作好了,接下來就是要把氣泡塞到咱們的ViewGroup裏了。dom

final ImageView imageView = new ImageView(getContext());
        //隨機選一個
        imageView.setImageDrawable(drawables[random.nextInt(3)]);
        imageView.setLayoutParams(layoutParams);
        addView(imageView);//放進ViewGroup

        Animator animator = getAnimator(imageView);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //view動畫結束後remove掉
                removeView(imageView);
            }
        });
        animator.start();複製代碼

上面代碼主要分爲三點:1.初始化一個氣泡view;2.添加到ViewGroup;3.獲取一個屬性動畫對象執行動畫,在這個動畫結束後把氣泡從ViewGroup裏removeView掉。ide

3.使view(氣泡)沿着貝塞爾曲線的軌跡移動;

OK,來到最後一個步驟,這是重點也是難點,其實說難不難說易不易,這特麼又是一句廢話~,先來思考一下咱們想要的效果,氣泡從左下角飄出,而後按照曲線的軌跡向屏幕的頂端飄去,有的很快,有的很慢,有的快快慢慢~~~既然如此,咱們先來把曲線的路徑的座標獲取到吧,咱們使用三階貝塞爾曲線公式:關於貝塞爾曲線呢,它很神祕也很神奇,關於它不只要學很長時間還要理解很長時間,就很少說了,在這隻放一個公式,而後推薦一篇博客[Android:貝塞爾曲線原理分析]

Paste_Image.png
Paste_Image.png

好的,來寫咱們自定義的插值器吧~

/**
 * 自定義插值器
 */
class BezierEvaluator implements TypeEvaluator<PointF> {
    //兩個控制點
    private PointF pointF1;
    private PointF pointF2;
    public BezierEvaluator(PointF pointF1, PointF pointF2) {
        this.pointF1 = pointF1;
        this.pointF2 = pointF2;
    }
    @Override
    public PointF evaluate(float time, PointF startValue,
                           PointF endValue) {
        float timeOn = 1.0f - time;
        PointF point = new PointF();
        //這麼複雜的公式讓我計算真心頭疼,可是計算機很easy
        point.x = timeOn * timeOn * timeOn * (startValue.x)
                + 3 * timeOn * timeOn * time * (pointF1.x)
                + 3 * timeOn * time * time * (pointF2.x)
                + time * time * time * (endValue.x);
        point.y = timeOn * timeOn * timeOn * (startValue.y)
                + 3 * timeOn * timeOn * time * (pointF1.y)
                + 3 * timeOn * time * time * (pointF2.y)
                + time * time * time * (endValue.y);
        //這裏返回的是曲線上每個點的座標值
        return point;
    }
}複製代碼

下面就來使用這個插值器吧,開始寫咱們的屬性動畫~

//初始化一個自定義的貝塞爾曲線插值器,而且傳入控制點
BezierEvaluator evaluator = new BezierEvaluator(getPointF(), getPointF());
//傳入了曲線起點(左下角)和終點(頂部隨機)
ValueAnimator animator = ValueAnimator.ofObject(evaluator, new PointF(0, getHeight())
        , new PointF(random.nextInt(getWidth()), -mViewHeight));
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        //獲取到貝塞爾曲線軌跡上的x和y值 賦值給view
        PointF pointF = (PointF) animation.getAnimatedValue();
        target.setX(pointF.x);
        target.setY(pointF.y);
    }
});
animator.setTarget(target);
animator.setDuration(5000);複製代碼

這裏面牽涉了一個控制點的獲取,咱們是採用隨機性的原則來獲取ViewGroup上的任何一點的座標來做爲曲線的控制點~

/**
 * 自定義曲線的兩個控制點,隨機在ViewGroup上的任何一個位置
 */
private PointF getPointF() {
    PointF pointF = new PointF();
    pointF.x = random.nextInt(mWidth);
    pointF.y = random.nextInt(mHeight);
    return pointF;
}複製代碼

最後再來初始化一個AnimatorSet把剛纔寫好的貝塞爾曲線的屬性動畫放進去便可,最後把這個AnimatorSet賦給最開始時候的animator就大功告成了。

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(bezierValueAnimator);
animatorSet.setInterpolator(interpolators[random.nextInt(4)]);
animatorSet.setTarget(target);複製代碼

最後在Activity中獲取該ViewGroup,隨便寫一個定時器源源不斷的往ViewGroup中添加氣泡便可。

按照慣例,把全家福放上來~

BalloonRelativeLayout.java

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.util.Random;

/**
 * Created by zhuyong on 2017/7/19.
 */

public class BalloonRelativeLayout extends RelativeLayout {
    private Context mContext;
    private Interpolator[] interpolators;//插值器數組
    private Interpolator linearInterpolator = new LinearInterpolator();// 以常量速率改變
    private Interpolator accelerateInterpolator = new AccelerateInterpolator();//加速
    private Interpolator decelerateInterpolator = new DecelerateInterpolator();//減速
    private Interpolator accelerateDecelerateInterpolator = new AccelerateDecelerateInterpolator();//先加速後減速
    private LayoutParams layoutParams;
    private int mHeight;
    private int mWidth;
    private Random random = new Random();//初始化隨機數類
    private int mViewHeight = dip2px(getContext(), 50);//默認50dp
    private Drawable[] drawables;

    public BalloonRelativeLayout(Context context) {
        this(context, null);
    }

    public BalloonRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BalloonRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        //初始化顯示的圖片
        drawables = new Drawable[3];
        Drawable mBalloon = ContextCompat.getDrawable(mContext, R.mipmap.balloon_pink);
        Drawable mBalloon2 = ContextCompat.getDrawable(mContext, R.mipmap.balloon_purple);
        Drawable mBalloon3 = ContextCompat.getDrawable(mContext, R.mipmap.balloon_blue);
        drawables[0] = mBalloon;
        drawables[1] = mBalloon2;
        drawables[2] = mBalloon3;

        //設置view寬高相等,默認都是50dp
        layoutParams = new LayoutParams(mViewHeight, mViewHeight);
        layoutParams.addRule(ALIGN_PARENT_BOTTOM, TRUE);

        // 初始化插值器
        interpolators = new Interpolator[4];
        interpolators[0] = linearInterpolator;
        interpolators[1] = accelerateInterpolator;
        interpolators[2] = decelerateInterpolator;
        interpolators[3] = accelerateDecelerateInterpolator;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
    }

    public void addBalloon() {
        final ImageView imageView = new ImageView(getContext());
        //隨機選一個
        imageView.setImageDrawable(drawables[random.nextInt(3)]);
        imageView.setLayoutParams(layoutParams);
        addView(imageView);

        Animator animator = getAnimator(imageView);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //view動畫結束後remove掉
                removeView(imageView);
            }
        });
        animator.start();
    }


    private Animator getAnimator(View target) {

        ValueAnimator bezierValueAnimator = getBezierValueAnimator(target);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playSequentially(bezierValueAnimator);
        animatorSet.setInterpolator(interpolators[random.nextInt(4)]);
        animatorSet.setTarget(target);
        return animatorSet;
    }

    private ValueAnimator getBezierValueAnimator(final View target) {

        //初始化一個自定義的貝塞爾曲線插值器,而且傳入控制點
        BezierEvaluator evaluator = new BezierEvaluator(getPointF(), getPointF());

        //傳入了曲線起點(左下角)和終點(頂部隨機)
        ValueAnimator animator = ValueAnimator.ofObject(evaluator, new PointF(0, getHeight())
                , new PointF(random.nextInt(getWidth()), -mViewHeight));
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //獲取到貝塞爾曲線軌跡上的x和y值 賦值給view
                PointF pointF = (PointF) animation.getAnimatedValue();
                target.setX(pointF.x);
                target.setY(pointF.y);
            }
        });
        animator.setTarget(target);
        animator.setDuration(5000);
        return animator;
    }


    /**
     * 自定義曲線的兩個控制點,隨機在ViewGroup上的任何一個位置
     */
    private PointF getPointF() {
        PointF pointF = new PointF();
        pointF.x = random.nextInt(mWidth);
        pointF.y = random.nextInt(mHeight);
        return pointF;
    }


    /**
     * 自定義插值器
     */

    class BezierEvaluator implements TypeEvaluator<PointF> {

        //途徑的兩個點
        private PointF pointF1;
        private PointF pointF2;

        public BezierEvaluator(PointF pointF1, PointF pointF2) {
            this.pointF1 = pointF1;
            this.pointF2 = pointF2;
        }

        @Override
        public PointF evaluate(float time, PointF startValue,
                               PointF endValue) {

            float timeOn = 1.0f - time;
            PointF point = new PointF();
            //這麼複雜的公式讓我計算真心頭疼,可是計算機很easy
            point.x = timeOn * timeOn * timeOn * (startValue.x)
                    + 3 * timeOn * timeOn * time * (pointF1.x)
                    + 3 * timeOn * time * time * (pointF2.x)
                    + time * time * time * (endValue.x);

            point.y = timeOn * timeOn * timeOn * (startValue.y)
                    + 3 * timeOn * timeOn * time * (pointF1.y)
                    + 3 * timeOn * time * time * (pointF2.y)
                    + time * time * time * (endValue.y);
            return point;
        }
    }

    /**
     * Dip into pixels
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}複製代碼

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<com.zhuyong.balloonrelativelayout.BalloonRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/balloonRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">
    <!--播放視頻-->
    <com.zhuyong.balloonrelativelayout.CustomVideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false" />

</com.zhuyong.balloonrelativelayout.BalloonRelativeLayout>複製代碼

MainActivity.java

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    private BalloonRelativeLayout mBalloonRelativeLayout;
    private VideoView mVideoView;

    private int TIME = 100;//這裏默認每隔100毫秒添加一個氣泡
    Handler mHandler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自帶方法實現定時器
            try {
                mHandler.postDelayed(this, TIME);
                mBalloonRelativeLayout.addBalloon();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消狀態欄
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        mVideoView = (VideoView) findViewById(R.id.videoView);
        mBalloonRelativeLayout = (BalloonRelativeLayout) findViewById(R.id.balloonRelativeLayout);
        initVideoView();
    }

    private void initVideoView() {
        //設置屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.mqr));
        //設置相關的監聽
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnCompletionListener(this);
    }

    //播放準備
    @Override
    public void onPrepared(MediaPlayer mp) {
        //開始播放
        mVideoView.start();
        mHandler.postDelayed(runnable, TIME);
    }

    //播放結束
    @Override
    public void onCompletion(MediaPlayer mp) {
        //開始播放
        mVideoView.start();
    }
}複製代碼

既然說了是全家福了,就把自定義VideoView也放進來把~主要是解決不能全屏顯示的問題~

CustomVideoView.java

import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;

/**
 * Created by zhuyong on 2017/7/20.
 * 自定義VideoView解決全屏問題
 */
public class CustomVideoView extends VideoView {
    public CustomVideoView(Context context) {
        this(context, null);
    }

    public CustomVideoView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }
}複製代碼

demo地址:

github.com/SuperKotlin…

若是你以爲此文對您有所幫助,歡迎入羣 QQ交流羣 : 232203809
微信公衆號:終端研發部

技術+職場
技術+職場
相關文章
相關標籤/搜索