欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

属性动画—仿58加载效果

程序员文章站 2022-05-29 18:16:25
...

属性动画—仿58加载效果
实现思路:
1、自定义view绘制圆、正方形、三角形;
2、将绘制好的view添加到布局容器中;
3、添加相应的动画效果;
自定义view,重写onMeasure()方法进行测量,重写onDraw()方法进行绘制;

public class ShapeView extends View {
    private Shape mCurrentShape = Shape.Circle;
    private Paint mPaint;
    private Path mPath;
    //圆形颜色
    private int mCircleColor = Color.BLUE;
    //正方形颜色
    private int mSquareColor = Color.RED;
    //三角形颜色
    private int mTriangleColor = Color.GREEN;


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

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

    public ShapeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShapeView);
        mCircleColor = array.getColor(R.styleable.ShapeView_circleColor, mCircleColor);
        mSquareColor = array.getColor(R.styleable.ShapeView_squareColor, mSquareColor);
        mTriangleColor = array.getColor(R.styleable.ShapeView_triangleColor, mTriangleColor);
        array.recycle();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        //宽高不一致时区最小值
        width = Math.min(width, height);
        height = Math.min(width, height);
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        switch (mCurrentShape) {
            case Circle:
                //画圆形
                int center = getWidth() / 2;
                mPaint.setColor(mCircleColor);
                canvas.drawCircle(center, center, center, mPaint);
                break;
            case Square:
                //画正方形
                mPaint.setColor(mSquareColor);
                canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
                break;
            case Triangle:
                //画三角形  绘制路线
                mPaint.setColor(mTriangleColor);
                if (mPath == null) {
                    mPath = new Path();
                    mPath.moveTo(getWidth() / 2, 0);
                    mPath.lineTo(0, (float) (getWidth() / 2 * Math.sqrt(3)));
                    mPath.lineTo(getWidth(), (float) (getWidth() / 2 * Math.sqrt(3)));
//                    path.lineTo(getWidth()/2,0);
                    //将绘制的路径闭合
                    mPath.close();
                }
                canvas.drawPath(mPath, mPaint);

                break;
        }
    }

    /**
     * 改变当前绘制的状态
     */
    public void exchange() {
        switch (mCurrentShape) {
            case Circle:
                mCurrentShape = Shape.Square;
                break;
            case Square:
                mCurrentShape = Shape.Triangle;
                break;
            case Triangle:
                mCurrentShape = Shape.Circle;
                break;
        }
        //进行绘制
        invalidate();
    }

    public enum Shape {
        Circle, Square, Triangle
    }

    public Shape getmCurrentShape() {
        return mCurrentShape;
    }
}

在onDraw()方法中调用canvas.drawCircle();绘制圆,canvas.drawRect();绘制正方形,对于三角形的绘制canvas类并没有提供相应的api可以进行调用,需要用到Path进行绘制,三角形本来就是三条线段连接起来的图形,使用Path进行线段绘制,然后再将其闭合就可以实现了;

view已经绘制好了,接下来是将其添加到自定义容器中;

/**
 * Created by Administrator on 2018/1/18.
 * 仿58加载数据动画效果
 */

public class LoadingView extends LinearLayout {
    private ShapeView mShapeView;//形状
    private View mShadowView;//阴影
    private int mTranslationDistance;
    //动画执行的时间
    private final long ANIMATOR_DURATION = 650;
    //是否停止动画
    private boolean mIsStopAnimator = false;

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

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

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

    /**
     * 初始化加载布局
     */
    private void initLayout() {
        //1.加载写好的ui_loading_view布局
        //1.1实例化view
        View loadView = inflate(getContext(), R.layout.ui_loading_view, null);
        //1.2添加到该view中
        addView(loadView);
        mShapeView = (ShapeView) loadView.findViewById(R.id.shape_view);
        mShadowView = loadView.findViewById(R.id.shadow_view);
        LinearLayout.LayoutParams params = (LayoutParams) mShapeView.getLayoutParams();
        mTranslationDistance = params.bottomMargin - dip2px(5);
        post(new Runnable() {
            @Override
            public void run() {
                startFallAnimator();
            }
        });
    }

    private int dip2px(int dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
    }

    /**
     * 开始下落动画
     */
    private void startFallAnimator() {
        if (mIsStopAnimator) {
            return;
        }
        //下落位移动画
        ObjectAnimator tanslation = ObjectAnimator.ofFloat(mShapeView, "translationY", 0, mTranslationDistance);
        //设置插值器
        tanslation.setInterpolator(new AccelerateInterpolator());
        tanslation.setDuration(ANIMATOR_DURATION);
        //配合阴影缩小
        ObjectAnimator shadowAniator = ObjectAnimator.ofFloat(mShadowView, "scaleX", 1f, 0.3f);
        shadowAniator.setDuration(ANIMATOR_DURATION);

        AnimatorSet set = new AnimatorSet();
        //一起执行动画
        set.playTogether(tanslation, shadowAniator);
        //下落后监听动画执行完毕
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //开始改变形状
                mShapeView.exchange();
                //上抛
                startUpAnimator();
            }
        });
        set.start();
    }

    /**
     * 执行上抛动画
     */
    private void startUpAnimator() {
        if (mIsStopAnimator) {
            return;
        }
        //上抛位移动画
        ObjectAnimator tanslation = ObjectAnimator.ofFloat(mShapeView, "translationY", mTranslationDistance, 0);
        //设置插值器
        tanslation.setInterpolator(new DecelerateInterpolator());
        tanslation.setDuration(ANIMATOR_DURATION);
        //配合阴影放大
        ObjectAnimator shadowAniator = ObjectAnimator.ofFloat(mShadowView, "scaleX", 0.3f, 1f);
        shadowAniator.setDuration(ANIMATOR_DURATION);

        AnimatorSet set = new AnimatorSet();
        //一起执行动画
        set.playTogether(tanslation, shadowAniator);
        //上抛后监听动画执行完毕
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //下落
                startFallAnimator();
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                startRotationAnimator();
            }
        });
        set.start();
    }

    /**
     * 上抛的时候需要旋转
     */
    private void startRotationAnimator() {
        if (mIsStopAnimator) {
            return;
        }
        ObjectAnimator rotationTanslation = null;
        switch (mShapeView.getmCurrentShape()) {
            case Circle:
            case Square:
                //180
                rotationTanslation = ObjectAnimator.ofFloat(mShapeView, "rotation", 0, 120);
                break;
            case Triangle:
                rotationTanslation = ObjectAnimator.ofFloat(mShapeView, "rotation", 0, -60);
                break;
        }
        rotationTanslation.setDuration(ANIMATOR_DURATION);
        rotationTanslation.setInterpolator(new DecelerateInterpolator());
        rotationTanslation.start();
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(View.INVISIBLE);//不要再去摆放和计算,少走一些系统的源码
        //清除掉动画
        mShapeView.clearAnimation();
        mShadowView.clearAnimation();
        //把LoadingView从父布局移除
        ViewGroup parent = (ViewGroup) getParent();
        if (parent != null) {
            parent.removeView(this);//从父布局移除
            //移除自己里面的所有View
            removeAllViews();
        }
        mIsStopAnimator = true;
    }
}

这里是采用xml布局解析的方式添加进来的;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <com.progressbardemo.ShapeView
        android:id="@+id/shape_view"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center_horizontal"
        app:circleColor="@color/circle"
        app:squareColor="@color/rect"
        app:triangleColor="@color/triangle"
        android:layout_marginBottom="82dp"
        android:layout_marginTop="10dp"/>
    <View
        android:id="@+id/shadow_view"
        android:layout_width="25dp"
        android:layout_height="3dp"
        android:background="@drawable/loading_shadow_bg" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="玩命加载中..."
        android:layout_marginTop="5dp"
        android:textSize="15sp"
        android:textColor="@android:color/black"/>
</LinearLayout>

包括位移、缩放、旋转动画也是在这里完成的;这样就ok了。

源码地址:
https://pan.baidu.com/s/1qZEqOXm