貝塞爾曲線之購物車動畫效果

question

  • 貝塞爾曲線是什么?
  • 貝塞爾曲線可以做什么?
  • 怎么做?

what is it?

貝塞爾曲線在百度定義是貝塞爾曲線(Bézier curve),又稱貝茲曲線或貝濟(jì)埃曲線,是應(yīng)用于二維圖形應(yīng)用程序的數(shù)學(xué)曲線。

1132780-253900d649118aa0.jpg

do what?

貝塞爾曲線根據(jù)不同點(diǎn)實(shí)現(xiàn)不同動態(tài)效果:

  • 一階貝塞爾曲線(兩點(diǎn)),繪制成一條直線
1359207897_7842.gif
  • 二階貝塞爾曲線(三點(diǎn))
1359208080_9518.gif
  • 三階貝塞爾曲線(四點(diǎn))
1359208177_9516.gif
  • 四階貝塞爾曲線(五點(diǎn))
20160402092908480.gif
  • 五階貝塞爾曲線(六點(diǎn))
20160405093717253.gif

看了上面貝塞爾曲線不同點(diǎn)不同效果后,相信大家都清楚貝塞爾曲線能干什么?沒錯(cuò),貝塞爾曲線能造高逼格動畫~~
就筆者目前了解的采用貝塞爾曲線實(shí)現(xiàn)的知名開源項(xiàng)目有:

  • QQ拖拽清除效果
  • 紙飛機(jī)刷新動畫
  • 滴油刷新動畫
  • 波浪動畫

到此大家是不是很興奮,想更多了解如何造一個(gè)高逼格貝塞爾曲線動畫。接下來我就給大家講述如何造一個(gè)基于貝塞爾曲線實(shí)現(xiàn)的購物車動畫,大家擦亮眼睛啦~~

1132780-2d7d1306d1b86b65.jpg

how to do it

思路

  • 確定動畫起終點(diǎn)
  • 在起終點(diǎn)之間使用二次貝塞爾曲線填充起終點(diǎn)之間點(diǎn)的軌跡
  • 設(shè)置屬性動畫,ValueAnimator插值器,獲取中間點(diǎn)的坐標(biāo)
  • 將執(zhí)行動畫控件的x、y坐標(biāo)設(shè)為上面得到的中間點(diǎn)坐標(biāo)
  • 開啟屬性動畫
  • 當(dāng)動畫結(jié)束時(shí)的操作

知識點(diǎn)

  • Android中提供了繪制一階、二階、三階的接口:
  • 一階接口:
public void lineTo(float x,float y)
  • 二階接口:
public void quadTo(float x1, float y1, float x2, float y2)
  • 三階接口:
public void cubicTo(float x1, float y1, float x2, float y2, float x3, float y3)
  • PathMeasure使用
  • getLength()
  • 理解 boolean getPosTan(float distance, float[] pos, float[] tan)
  • 如何獲取控件在屏幕中的絕對坐標(biāo)
  • int[] location = new int[2]; view.getLocationInWindow(location); 得到view在屏幕中的絕對坐標(biāo)。
  • 理解屬性動畫插值器ValueAnimator

code

首先寫購物車布局xml,代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rly_bezier_curve_shopping_cart"
    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">

    <FrameLayout
        android:id="@+id/fly_bezier_curve_shopping_cart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:paddingRight="30dp"
        android:layout_alignParentStart="true">
        <ImageView
            android:id="@+id/iv_bezier_curve_shopping_cart"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_gravity="right"
            android:src="@drawable/menu_shop_car_selected" />
        <TextView
            android:id="@+id/tv_bezier_curve_shopping_cart_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/white"
            android:background="@drawable/corner_view"
            android:text="0"
            android:layout_gravity="right"/>
    </FrameLayout>

    <ListView
        android:id="@+id/lv_bezier_curve_shopping_cart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/fly_bezier_curve_shopping_cart"/>
</RelativeLayout>

然后寫購物車適配器、實(shí)體類,代碼如下:

/**
 * @className: GoodsAdapter
 * @classDescription: 購物車商品適配器
 * @author: leibing
 * @createTime: 2016/09/28
 */
public class GoodsAdapter extends BaseAdapter{
    // 數(shù)據(jù)源(購物車商品圖片)
    private ArrayList<GoodsModel> mData;
    // 布局
    private LayoutInflater mLayoutInflater;
    // 回調(diào)監(jiān)聽
    private CallBackListener mCallBackListener;

    /**
     * 構(gòu)造函數(shù)
     * @author leibing
     * @createTime 2016/09/28
     * @lastModify 2016/09/28
     * @param context 上下文
     * @param mData 數(shù)據(jù)源(購物車商品圖片)
     * @return
     */
    public GoodsAdapter(Context context, ArrayList<GoodsModel> mData){
        mLayoutInflater = LayoutInflater.from(context);
        this.mData = mData;
    }

    @Override
    public int getCount() {
        return mData != null ? mData.size(): 0;
    }

    @Override
    public Object getItem(int i) {
        return mData != null ? mData.get(i): null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (view == null){
            view = mLayoutInflater.inflate(R.layout.adapter_shopping_cart_item, null);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        }else {
            // 復(fù)用ViewHolder
            viewHolder = (ViewHolder) view.getTag();
        }

        // 更新UI
        if (i < mData.size())
            viewHolder.updateUI(mData.get(i));

        return view;
    }

    /**
     * @className: ViewHolder
     * @classDescription: 商品ViewHolder
     * @author: leibing
     * @createTime: 2016/09/28
     */
    class  ViewHolder{
        // 顯示商品圖片
        private ImageView mShoppingCartItemIv;
        
        /**
         * 構(gòu)造函數(shù)
         * @author leibing
         * @createTime 2016/09/28
         * @lastModify 2016/09/28
         * @param view 視圖
         * @return
         */
        public ViewHolder(View view){
            // findView
            mShoppingCartItemIv = (ImageView) view.findViewById(R.id.iv_shopping_cart_item);
            // onClick
            view.findViewById(R.id.tv_shopping_cart_item).setOnClickListener(
                    new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mShoppingCartItemIv != null && mCallBackListener != null)
                        mCallBackListener.callBackImg(mShoppingCartItemIv);
                }
            });
        }

        /**
         * 更新UI
         * @author leibing
         * @createTime 2016/09/28
         * @lastModify 2016/09/28
         * @param goods 商品實(shí)體對象
         * @return
         */
        public void updateUI(GoodsModel goods){
            if (goods != null
                    && goods.getmGoodsBitmap() != null
                    && mShoppingCartItemIv != null)
                mShoppingCartItemIv.setImageBitmap(goods.getmGoodsBitmap());
        }
    }

    /**
     * 設(shè)置回調(diào)監(jiān)聽
     * @author leibing
     * @createTime 2016/09/28
     * @lastModify 2016/09/28
     * @param mCallBackListener 回調(diào)監(jiān)聽
     * @return
     */
    public void setCallBackListener(CallBackListener mCallBackListener){
        this.mCallBackListener = mCallBackListener;
    }

    /**
     * @interfaceName: CallBackListener
     * @interfaceDescription: 回調(diào)監(jiān)聽
     * @author: leibing
     * @createTime: 2016/09/28
     */
    public interface CallBackListener{
        void callBackImg(ImageView goodsImg);
    }
}

然后寫添加數(shù)據(jù)源以及設(shè)置適配器,代碼如下:

    // 購物車父布局
    private RelativeLayout mShoppingCartRly;
    // 購物車列表顯示
    private ListView mShoppingCartLv;
    // 購物數(shù)目顯示
    private TextView mShoppingCartCountTv;
    // 購物車圖片顯示
    private ImageView mShoppingCartIv;
    // 購物車適配器
    private GoodsAdapter mGoodsAdapter;
    // 數(shù)據(jù)源(購物車商品圖片)
    private ArrayList<GoodsModel> mData;
    // 貝塞爾曲線中間過程點(diǎn)坐標(biāo)
    private float[] mCurrentPosition = new float[2];
    // 路徑測量
    private PathMeasure mPathMeasure;
    // 購物車商品數(shù)目
    private int goodsCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // findView
        mShoppingCartLv = (ListView) findViewById(R.id.lv_bezier_curve_shopping_cart);
        mShoppingCartCountTv = (TextView) findViewById(R.id.tv_bezier_curve_shopping_cart_count);
        mShoppingCartRly = (RelativeLayout) findViewById(R.id.rly_bezier_curve_shopping_cart);
        mShoppingCartIv = (ImageView) findViewById(R.id.iv_bezier_curve_shopping_cart);
        // 是否顯示購物車商品數(shù)目
        isShowCartGoodsCount();
        // 添加數(shù)據(jù)源
        addData();
        // 設(shè)置適配器
        setAdapter();
    }

    /**
     * 設(shè)置適配器
     * @author leibing
     * @createTime 2016/09/28
     * @lastModify 2016/09/28
     * @param
     * @return
     */
    private void setAdapter() {
        // 初始化適配器
        mGoodsAdapter = new GoodsAdapter(this, mData);
        // 設(shè)置適配器監(jiān)聽
        mGoodsAdapter.setCallBackListener(new GoodsAdapter.CallBackListener() {
            @Override
            public void callBackImg(ImageView goodsImg) {
                // 添加商品到購物車
                addGoodsToCart(goodsImg);
            }
        });
        // 設(shè)置適配器
        mShoppingCartLv.setAdapter(mGoodsAdapter);
    }

接下來寫最重要的一塊,添加商品到購物車,代碼如下:

    /**
     * 添加商品到購物車
     * @author leibing
     * @createTime 2016/09/28
     * @lastModify 2016/09/28
     * @param goodsImg 商品圖標(biāo)
     * @return
     */
    private void addGoodsToCart(ImageView goodsImg) {
        // 創(chuàng)造出執(zhí)行動畫的主題goodsImg(這個(gè)圖片就是執(zhí)行動畫的圖片,從開始位置出發(fā),經(jīng)過一個(gè)拋物線(貝塞爾曲線),移動到購物車?yán)铮?        final ImageView goods = new ImageView(this);
        goods.setImageDrawable(goodsImg.getDrawable());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        mShoppingCartRly.addView(goods, params);

        // 得到父布局的起始點(diǎn)坐標(biāo)(用于輔助計(jì)算動畫開始/結(jié)束時(shí)的點(diǎn)的坐標(biāo))
        int[] parentLocation = new int[2];
        mShoppingCartRly.getLocationInWindow(parentLocation);

        // 得到商品圖片的坐標(biāo)(用于計(jì)算動畫開始的坐標(biāo))
        int startLoc[] = new int[2];
        goodsImg.getLocationInWindow(startLoc);

        // 得到購物車圖片的坐標(biāo)(用于計(jì)算動畫結(jié)束后的坐標(biāo))
        int endLoc[] = new int[2];
        mShoppingCartIv.getLocationInWindow(endLoc);

        // 開始掉落的商品的起始點(diǎn):商品起始點(diǎn)-父布局起始點(diǎn)+該商品圖片的一半
        float startX = startLoc[0] - parentLocation[0] + goodsImg.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + goodsImg.getHeight() / 2;

        // 商品掉落后的終點(diǎn)坐標(biāo):購物車起始點(diǎn)-父布局起始點(diǎn)+購物車圖片的1/5
        float toX = endLoc[0] - parentLocation[0] + mShoppingCartIv.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

        // 開始繪制貝塞爾曲線
        Path path = new Path();
        // 移動到起始點(diǎn)(貝塞爾曲線的起點(diǎn))
        path.moveTo(startX, startY);
        // 使用二階貝塞爾曲線:注意第一個(gè)起始坐標(biāo)越大,貝塞爾曲線的橫向距離就會越大,一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        // mPathMeasure用來計(jì)算貝塞爾曲線的曲線長度和貝塞爾曲線中間插值的坐標(biāo),如果是true,path會形成一個(gè)閉環(huán)
        mPathMeasure = new PathMeasure(path, false);

        // 屬性動畫實(shí)現(xiàn)(從0到貝塞爾曲線的長度之間進(jìn)行插值計(jì)算,獲取中間過程的距離值)
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);

        // 勻速線性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 當(dāng)插值計(jì)算進(jìn)行時(shí),獲取中間的每個(gè)值,
                // 這里這個(gè)值是中間過程中的曲線長度(下面根據(jù)這個(gè)值來得出中間點(diǎn)的坐標(biāo)值)
                float value = (Float) animation.getAnimatedValue();
                // 獲取當(dāng)前點(diǎn)坐標(biāo)封裝到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) :
                // 傳入一個(gè)距離distance(0<=distance<=getLength()),然后會計(jì)算當(dāng)前距離的坐標(biāo)點(diǎn)和切線,pos會自動填充上坐標(biāo),這個(gè)方法很重要。
                // mCurrentPosition此時(shí)就是中間距離點(diǎn)的坐標(biāo)值
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                // 移動的商品圖片(動畫圖片)的坐標(biāo)設(shè)置為該中間點(diǎn)的坐標(biāo)
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });

        // 開始執(zhí)行動畫
        valueAnimator.start();

        // 動畫結(jié)束后的處理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // 購物車商品數(shù)量加1
                goodsCount ++;
                isShowCartGoodsCount();
                mShoppingCartCountTv.setText(String.valueOf(goodsCount));
                // 把執(zhí)行動畫的商品圖片從父布局中移除
                mShoppingCartRly.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }
1132780-f58fe3a5c5a7c281.jpg

代碼分析完畢,一個(gè)高逼格貝塞爾曲線實(shí)現(xiàn)的購物車添加商品動畫效果實(shí)現(xiàn)分析完畢~~

效果圖如下:

BezierCurveShoppingCart.gif

筆者文筆太糟,歡迎吐槽,如有不對之處,請留言指點(diǎn)~~

呼吁大家動手實(shí)踐,一切將會變得很容易~~~

項(xiàng)目地址:BezierCurveShoppingCart

關(guān)于作者

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容