Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AnimatedPathView 實現會動的圖片標簽

編輯:關於 Android 程式設計

我很早就用過小紅書,對它客戶端「筆記」這塊的設計頗有好感。恰好去年所在的公司也處在競爭對手的位置,出於產品社交化的考慮,社區分享模塊多少參照了類似思路,其中就有一個頗有意思的貼紙與標簽設計(這部分用到了 GpuImage 庫,demo 代碼已開源,感興趣可以去我的 GitHub 上 fork)。

本文要說的是詳情頁裡那個可以動起來的標簽。之前項目趕工期,這個效果是用 H5 实现的;後來轉到 React Native 反而更好做了。這裡記錄一下純 Android 的實現方式。

先看效果:

思路分析

效果可以拆成三塊:線條的繪製、圓點的閃爍、文字的繪製。

線條本身很簡單,canvas.drawLine 就能畫,但那是「死」的線,無法呈現生長動畫。Java 提供了另一條路:用 Path 配合 PathEffect。之前做手寫板項目的時候就是這麼處理的——通過改變 PathEffect 的偏移量,控制 path 顯示的長度,動畫效果自然就出來了。PathEffect 有多個子類,可以實現虛線、圓點線等不同風格,這裡不再展開。

float percentage = 0.0f;
PathEffect effect = new DashPathEffect(
        new float[]{pathLength, pathLength},
        pathLength - pathLength * percentage);

AnimatedPathView 完整代碼

public class AnimatedPathView extends View {

    private Paint mPaint;
    private Path mPath;

    private int mStrokeColor = Color.parseColor("#ff6c6c");
    private int mStrokeWidth = 8;
    private float mProgress = 0f;
    private float mPathLength = 0f;

    private float circleX = 0f;
    private float circleY = 0f;
    private int radius = 0;

    private String pathText = "化妝包...";
    private int textX, textY;

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

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

    public AnimatedPathView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimatedPathView);
        mStrokeColor = a.getColor(R.styleable.AnimatedPathView_pathColor,
                Color.parseColor("#ff6c6c"));
        mStrokeWidth = a.getInteger(R.styleable.AnimatedPathView_pathWidth, 8);
        a.recycle();
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(mStrokeColor);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setAntiAlias(true);
        setPath(new Path());
    }

    public void setPath(Path p) {
        mPath = p;
        PathMeasure measure = new PathMeasure(mPath, false);
        mPathLength = measure.getLength();
    }

    public void setPathText(String pathText, int textX, int textY) {
        this.pathText = pathText;
        this.textX = textX;
        this.textY = textY;
    }

    public void setPath(float[]... points) {
        if (points.length == 0) {
            throw new IllegalArgumentException("Cannot have zero points in the line");
        }
        Path p = new Path();
        p.moveTo(points[0][0], points[0][1]);
        for (int i = 1; i < points.length; i++) {
            p.lineTo(points[i][0], points[i][1]);
        }
        // 以第一個坐標點作為圓點的繪製原點
        circleX = points[0][0] - radius / 2;
        circleY = points[0][1] - radius / 2;
        setPath(p);
    }

    /** 動畫驅動入口:0 ~ 1 */
    public void setPercentage(float percentage) {
        if (percentage < 0.0f || percentage > 1.0f) {
            throw new IllegalArgumentException("setPercentage not between 0.0f and 1.0f");
        }
        mProgress = percentage;
        invalidate();
    }

    public void scalePathBy(float x, float y) {
        Matrix m = new Matrix();
        m.postScale(x, y);
        mPath.transform(m);
        PathMeasure measure = new PathMeasure(mPath, false);
        mPathLength = measure.getLength();
    }

    public void scaleCircleRadius(int radius) {
        this.radius = radius;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // drawCircle(canvas);      // 繪製圓點
        drawPathEffect(canvas);     // 繪製線條
        drawText(canvas);           // 繪製文字
        canvas.restore();
    }

    private void drawText(Canvas canvas) {
        mPaint.setTextSize(28);
        mPaint.setColor(Color.parseColor("#ffffff"));
        if (canvas != null && !TextUtils.isEmpty(pathText)) {
            canvas.drawText(pathText, textX, textY, mPaint);
        }
        invalidate();
    }

    private void drawPathEffect(Canvas canvas) {
        PathEffect pathEffect = new DashPathEffect(
                new float[]{mPathLength, mPathLength},
                mPathLength - mPathLength * mProgress);
        mPaint.setPathEffect(pathEffect);
        mPaint.setStrokeWidth(4);
        mPaint.setColor(Color.parseColor("#ffffff"));
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        canvas.drawPath(mPath, mPaint);
    }

    private void drawCircle(Canvas canvas) {
        mPaint.setStrokeWidth(25);
        mPaint.setColor(Color.parseColor("#ffffff"));
        canvas.drawCircle(circleX, circleY, radius, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int measuredWidth;
        int measuredHeight;
        // 不支持 wrap_content,必須指定明確尺寸
        if (widthMode == MeasureSpec.AT_MOST) {
            throw new IllegalStateException("AnimatedPathView cannot have a WRAP_CONTENT property");
        } else {
            measuredWidth = widthSize;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            throw new IllegalStateException("AnimatedPathView cannot have a WRAP_CONTENT property");
        } else {
            measuredHeight = heightSize;
        }
        setMeasuredDimension(measuredWidth, measuredHeight);
    }
}

這份代碼在基礎實現上補充了不少判斷,以適應本文的場景。到目前為止只解決了畫線的問題,那圓點的閃爍怎麼辦?其實很簡單——用視圖動畫即可,而且我們大可以把「閃爍的圓點 + 生長的線條」封裝進一個自定義容器:

PointView:把標簽封裝起來

public class PointView extends FrameLayout {

    private Context mContext;
    private List<PointScaleBean> points;
    private FrameLayout layouPoints;
    private AnimatedPathView animatedPath;
    private int radius = 10;
    private String text = "圖文標簽 $99.00";

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

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

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

    private void initView(Context context, AttributeSet attrs) {
        this.mContext = context;
        View root = inflate(context, R.layout.layout_point, this);
        layouPoints = (FrameLayout) root.findViewById(R.id.layouPoints);
        animatedPath = (AnimatedPathView) root.findViewById(R.id.animated_path);
    }

    public void addPoints(int width, int height) {
        addPoint(width, height);
    }

    public void setPoints(List<PointScaleBean> points) {
        this.points = points;
    }

    private void addPoint(int width, int height) {
        layouPoints.removeAllViews();
        for (int i = 0; i < points.size(); i++) {
            double widthScale = points.get(i).widthScale;
            double heightScale = points.get(i).heightScale;

            LinearLayout view = (LinearLayout) LayoutInflater.from(mContext)
                    .inflate(R.layout.layout_img_point, this, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.imgPoint);
            imageView.setTag(i);

            // 啟動幀動畫,實現圓點閃爍
            AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();

            LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
            layoutParams.leftMargin = (int) (width * widthScale);
            layoutParams.topMargin = (int) (height * heightScale);
            layouPoints.addView(view, layoutParams);
        }
        initView();
        initPathAnimated();
    }

    private void initPathAnimated() {
        ViewTreeObserver observer = animatedPath.getViewTreeObserver();
        if (observer != null) {
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    animatedPath.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    animatedPath.scaleCircleRadius(radius);
                    animatedPath.scalePathBy(
                            animatedPath.getWidth() / 2,
                            animatedPath.getHeight() / 2);

                    float[][] pathPoints = new float[][]{
                            {animatedPath.getWidth() / 2 - radius / 2,
                             animatedPath.getHeight() / 2 - radius / 2},
                            {animatedPath.getWidth() / 2 - UIUtils.dp2px(mContext, 30),
                             animatedPath.getHeight() / 2 - UIUtils.dp2px(mContext, 40)},
                            {animatedPath.getWidth() / 2 - UIUtils.dp2px(mContext, 150),
                             animatedPath.getHeight() / 2 - UIUtils.dp2px(mContext, 40)}
                    };
                    animatedPath.setPath(pathPoints);
                }
            });
        }
    }

    private void initView() {
        animatedPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 點擊觸發線條生長動畫
                ObjectAnimator anim = ObjectAnimator.ofFloat(view, "percentage", 0.0f, 1.0f);
                anim.setDuration(2000);
                anim.setInterpolator(new LinearInterpolator());
                anim.start();
            }
        });
    }
}

配套的佈局與資源

layout_point.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.yju.app.widght.path.AnimatedPathView
        android:id="@+id/animated_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <FrameLayout
            android:id="@+id/layouPoints"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </com.yju.app.widght.path.AnimatedPathView>
</FrameLayout>

layout_img_point.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgPoint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/point_img" />
</LinearLayout>

閃爍的圓點用的是幀動畫:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/point_img1" android:duration="100" />
    <item android:drawable="@drawable/point_img2" android:duration="100" />
    <!-- 中間省略若干幀 -->
    <item android:drawable="@drawable/point_img13" android:duration="100" />
</animation-list>

最後在 MainActivity 中按比例擺放標簽即可:

private void initPointView() {
    List<PointScaleBean> list = new ArrayList<>();
    PointScaleBean point = new PointScaleBean();
    point.widthScale = 0.36f;
    point.heightScale = 0.75f;
    list.add(point);

    pointView.setPoints(list);
    pointView.addPoints(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
}

佈局上我的做法比較取巧:給父容器加一張背景圖。實際項目中寫一個相對佈局就能實現實時效果了。思路是這樣,具體展現形式可以按業務自由發揮。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved