教你一步一步实现图标无缝变形切换

2,429 阅读9分钟

我的简书同步发布:教你一步一步实现图标无缝变形切换 ☺欢迎打赏☺

转载请注明出处:【huachao1001的专栏:http://blog.csdn.net/huachao1001】

*本篇文章已授权微信公众号 guolin_blog (郭霖)独家发布

本来这篇文章几天前就应该写好并发布出来的,由于要写小论文,被导师劈头盖脸的骂了几天,一直在搞论文,耽误了博文的编写。今天终于把小论文给投出去了,终于可以好好写博客了!

在上一篇文章《酷炫的Activity切换动画,打造更好的用户体验 》中,我们感受到了过渡切换动画带来的不一样的用户体验。如何你还意犹未尽,那么今天我们再体验一把图标切换动画。之前看过Material Design的图标切换,如下图:

图标切换

感觉效果挺好的,但是发现很多实现是通过多个图片切换产生的动画效果。如果想要定制属于自己的切换效果显然得要去制作很多张图片,导致apk变大不说,这得需要一定的flash功底啊~,于是我就想是否可以通过属性动画,根据起始path数据和最终的path数据产生动画效果。先来个我们的最终效果图,让你更有动力往下看(PS:以下gif是放慢了的动画,另外gif丢帧导致不流畅,各位不要觉得很卡哈~):

Path变形旋转切换加减变形

在API 21后,系统内置了AnimatedVectorDrawable ,它能将两个Path以动画方式切换。可是,毕竟不兼容5.0之前的版本,这个类还是过几年再用吧~。既然不用AnimatedVectorDrawable 类,我们就自己写一个呗~。

SVG绘制路径的命令虽然不多,如下(参考【W3School中SVG path教程】):

M : 相当于moveTo 两个参数表示移动终点位置的x,y
L :相当于lineto 两个参数表示x ,y
H :相当于水平的Line to,需要一个参数表示lineto的x坐标,y坐标则是当前绘制点的坐标
V :相当于垂直的line to需要一个参数表示lineto的y坐标
C :curveto(相当于cubicTo,需要6个参数,分别表示第1、2控制点坐标以及结束点的坐标
S :4个参数,表示平滑的使用3阶贝塞尔曲线,另一个控制点坐标被省略,需要我们去计算
Q :二阶贝塞尔曲线,4个参数,分别表示控制点和结束点坐标
T :平滑使用二阶贝塞尔曲线,只有2个参数表示结束点,控制点需要我们计算
A :绘制弧线,参数比较复杂,有7个参数
Z :相当于close path,无参数

其中S、T、A几个命令较复杂,本文先不去实现这几个命令,感兴趣的童鞋可以自己去实现。首先,一个Path是由多个Path组成,由于需要实现动画效果,也就是Path里面的数据我们需要动态变化,我们把各个Path“片段”封装到一个对象中。一个“片段”对应一个svg path的命令,因为参数最多是3个点(Point),我们只需封装3个Point对象:

class FragmentPath {
    
    public PathType pathType;
    
    public int dataLen;
    public Point p1;
    public Point p2;
    public Point p3;
}

其中,PathType是枚举类型,枚举类型无需加V、H命令,因为V、H在最终绘制的时候还是要转为Line To,dataLen参数用于记录当前的命令所占的字符串长度。PathType枚举类型如下:

  enum PathType {
    MOVE, LINE_TO, CURVE_TO, QUAD_TO,  CLOSE
}

对SVG path的操作太多,我们把这些操作单独封装到一个SVGUtil中,并将其设置为单例模式:

package com.hc.transformicon;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.Path;
import android.graphics.Point;
import android.util.Log;

public class SVGUtil {
    private static volatile SVGUtil svgUtil;
    private Set svgCommandSet;
    private String[] command = { "M", "L", "H", "V", "C", "S", "Q", "T", "A",
            "Z" };

    private SVGUtil() {
        svgCommandSet = new HashSet();
        for (String cmd : command) {
            svgCommandSet.add(cmd);
        }

    }

    public static SVGUtil getInstance() {
        if (svgUtil == null) {
            synchronized (SVGUtil.class) {
                if (svgUtil == null) {
                    svgUtil = new SVGUtil();
                }
            }
        }
        return svgUtil;
    }
    static class FragmentPath {
        
        public PathType pathType;
        
        public int dataLen;
        public Point p1;
        public Point p2;
        public Point p3;
    }
    static enum PathType {
        MOVE, LINE_TO, CURVE_TO, QUAD_TO, ARC, CLOSE
    }

}

由于SVG path中的数据可能写的格式不同,比如使用M命令,有些人会写成:M 100 100而有些人会写成M 100,100这还算好的了,因为看起来比较“规矩”,以空格或逗号分隔字符串就可以提取数据。有些人可能会写成M100,100,也就是在命令字母两边没有加空格,这就让你没办法提取数据了。另外还有就是用户不小心多加了几个空格,或者多加了几个逗号,这让你读取也会带来很多麻烦。还有就是用户还可能把M写成小写的m,在SVG中大小写的含义是不同的,但是我们不是去实现标准的SVG显示,我们可以去忽略大小写,我们只是借鉴一下SVG的命令,顺带学习一下SVG而已。说了那么多,就是为了引入一个话题:需要对用户原始数据进行预处理,在SVGUtil类中添加如下函数:


public ArrayList extractSvgData(String svgData) {
    
    
    Set hasReplaceSet = new HashSet();
    
    Pattern pattern = Pattern.compile("[a-zA-Z]");
    Matcher matcher = pattern.matcher(svgData);
    
    while (matcher.find()) {
        
        String s = matcher.group();
        
        if (!hasReplaceSet.contains(s)) {
            svgData = svgData.replace(s, " " + s + " ");
            hasReplaceSet.add(s);
        }
    }
    
    
    svgData = svgData.replace(",", " ").trim().toUpperCase();
    
    String[] ss = svgData.split(" ");
    
    ArrayList data = new ArrayList();
    for (String s : ss) {
        
        
        if (s != null && !"".equals(s)) {
            data.add(s);
        }
    }
    return data;
}

对原始数据做了预处理后,开始真正的将数据转换为Path对象了,在SVGUtil类中添加如下函数:




public Path parsePath(ArrayList svgDataList, float widthFactor,
        float heightFactor) {
    
    Path path = new Path();
    
    int startIndex = 0;
    
    Point lastPoint = new Point(0, 0);
    
    FragmentPath fp = nextFrag(svgDataList, startIndex, lastPoint);
    
    while (fp != null) {
        
        switch (fp.pathType) {
        case MOVE: {
            path.moveTo(fp.p1.x * widthFactor, fp.p1.y * heightFactor);
            lastPoint = fp.p1;
            break;
        }
        case LINE_TO: {
            path.lineTo(fp.p1.x * widthFactor, fp.p1.y * heightFactor);
            lastPoint = fp.p1;
            break;
        }
        case CURVE_TO: {
            path.cubicTo(fp.p1.x * widthFactor, fp.p1.y * heightFactor,
                    fp.p2.x * widthFactor, fp.p2.y * heightFactor, fp.p3.x
                            * widthFactor, fp.p3.y * heightFactor);
            lastPoint = fp.p3;
            break;
        }
        case QUAD_TO: {
            path.quadTo(fp.p1.x * widthFactor, fp.p1.y * heightFactor,
                    fp.p2.x * widthFactor, fp.p2.y * heightFactor);
            lastPoint = fp.p2;
            break;
        }

        case CLOSE: {
            path.close();
        }
        default:
            break;
        }
        
        startIndex = startIndex + fp.dataLen + 1;
        fp = nextFrag(svgDataList, startIndex, lastPoint);
    }
    return path;
}

我们看到,参数中有宽高的放缩倍数。为什么需要放缩倍数呢?我们知道,SVG是矢量图,放缩后图片清晰度是无影响的,因此我们这里需要加放缩倍数。另外我们注意到还有个nextFrag函数,用于提取下一条命令,并封装为FragmentPath对象,在SVGUtil类中添加如下函数:


private FragmentPath nextFrag(ArrayList svgData, int startIndex,
        Point lastPoint) {
    if (svgData == null)
        return null;
    int svgDataSize = svgData.size();
    if (startIndex >= svgDataSize)
        return null;
    
    int i = startIndex + 1;
    
    int length = 0;
    FragmentPath fp = new FragmentPath();
    
    while (i < svgDataSize) {
        if (svgCommandSet.contains(svgData.get(i)))
            break;
        i++;
        length++;
    }
    
    fp.dataLen = length; 
    
    switch (length) {
    case 0: {
        Log.d("", svgData.get(startIndex) + " none data");
        break;
    }
    case 1: {
        int d = (int) Float.parseFloat(svgData.get(startIndex + 1));
        if (svgData.get(startIndex).equals("H")) {
            fp.p1 = new Point(d, lastPoint.y);

        } else {
            fp.p1 = new Point(lastPoint.x, d);

        }

        break;
    }
    case 2: {
        int x = (int) Float.parseFloat(svgData.get(startIndex + 1));
        int y = (int) Float.parseFloat(svgData.get(startIndex + 2));
        fp.p1 = new Point(x, y);

        break;
    }
    case 4: {
        int x1 = (int) Float.parseFloat(svgData.get(startIndex + 1));
        int y1 = (int) Float.parseFloat(svgData.get(startIndex + 2));
        int x2 = (int) Float.parseFloat(svgData.get(startIndex + 3));
        int y2 = (int) Float.parseFloat(svgData.get(startIndex + 4));
        fp.p1 = new Point(x1, y1);
        fp.p2 = new Point(x2, y2);

        break;
    }
    case 6: {
        int x1 = (int) Float.parseFloat(svgData.get(startIndex + 1));
        int y1 = (int) Float.parseFloat(svgData.get(startIndex + 2));
        int x2 = (int) Float.parseFloat(svgData.get(startIndex + 3));
        int y2 = (int) Float.parseFloat(svgData.get(startIndex + 4));
        int x3 = (int) Float.parseFloat(svgData.get(startIndex + 5));
        int y3 = (int) Float.parseFloat(svgData.get(startIndex + 6));
        fp.p1 = new Point(x1, y1);
        fp.p2 = new Point(x2, y2);
        fp.p3 = new Point(x3, y3);

        break;
    }
    default:
        break;
    }
    
    switch (svgData.get(startIndex)) {
    case "M": {
        fp.pathType = PathType.MOVE;
        break;
    }
    case "H":
    case "V":
    case "L": {
        fp.pathType = PathType.LINE_TO;
        break;
    }

    case "C": {
        fp.pathType = PathType.CURVE_TO;
        break;
    }

    case "Q": {
        fp.pathType = PathType.QUAD_TO;
        break;
    }
    case "Z": {
        fp.pathType = PathType.CLOSE;
        break;
    }

    }
    return fp;
}

接下来就是自定义View了,由于接下来我们需要实现动画效果,因此我们就将自定义的View继承SurfaceView:

package com.hc.transformicon;

import java.util.ArrayList;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Bitmap.Config;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

/**
 * Created by HuaChao on 2016/6/17.
 */
public class SVGPathView extends SurfaceView implements SurfaceHolder.Callback {

    
    private ArrayList svgStartDataList;
    
    private ArrayList svgEndDataList;

    private SurfaceHolder surfaceHolder;
    
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Paint mPaint;
    
    private int mWidth;
    private int mHeight;
    
    private int mViewWidth;
    private int mViewHeight;
    
    private int mPaintWidth;

    
    private float widthFactor;
    private float heightFactor;
    private int mPaintColor;

    public SVGPathView(Context context) {
        super(context);
        init();
    }

    public SVGPathView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.SVGPathView);
        
        String svgStartPath = ta
                .getString(R.styleable.SVGPathView_svg_start_path);
        String svgEndPath = ta.getString(R.styleable.SVGPathView_svg_end_path);
        
        if (svgStartPath == null && svgEndPath != null) {
            svgStartPath = svgEndPath;
        } else if (svgStartPath != null && svgEndPath == null) {
            svgEndPath = svgStartPath;
        }
        
        mViewWidth = ta.getInteger(R.styleable.SVGPathView_svg_view_width, -1);
        mViewHeight = ta
                .getInteger(R.styleable.SVGPathView_svg_view_height, -1);
        mPaintWidth = ta.getInteger(R.styleable.SVGPathView_svg_paint_width, 5);
        mPaintColor = ta.getColor(R.styleable.SVGPathView_svg_color,
                Color.BLACK);
        
        svgStartDataList = SVGUtil.getInstance().extractSvgData(svgStartPath);
        svgEndDataList = SVGUtil.getInstance().extractSvgData(svgEndPath);

        ta.recycle();
        init();
    }

    
    private void init() {
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        mPaint = new Paint();
        mPaint.setStrokeJoin(Join.ROUND);
        mPaint.setStrokeCap(Cap.ROUND);
        mPaint.setColor(mPaintColor);

    }

    
    public void drawPath() {
        clearCanvas();
        mPaint.setStyle(Style.STROKE);
        mPaint.setColor(mPaintColor);
        Path path = SVGUtil.getInstance().parsePath(svgStartDataList,
                widthFactor, heightFactor);
        mCanvas.drawPath(path, mPaint);
        Canvas canvas = surfaceHolder.lockCanvas();
        canvas.drawBitmap(mBitmap, 0, 0, mPaint);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    
    private void clearCanvas() {
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Style.FILL);
        mCanvas.drawRect(0, 0, mWidth, mHeight, mPaint);

    }

    
    @Override
    public void invalidate() {
        super.invalidate();
        Canvas canvas = surfaceHolder.lockCanvas();
        canvas.drawBitmap(mBitmap, 0, 0, mPaint);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        
        mWidth = width;
        mHeight = height;
        
        if (mViewWidth <= 0) {
            mViewWidth = width;
        }
        if (mViewHeight <= 0) {
            mViewHeight = height;
        }
        
        widthFactor = 1.f * width / mViewWidth;
        heightFactor = 1.f * height / mViewHeight;
        
        mBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        
        mPaint.setStrokeWidth(mPaintWidth * widthFactor);
        
        clearCanvas();
        
        invalidate();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

}

最后,再看看我们的布局文件以及自定义的布局属性:
styles.xml添加如下:



    
    
    
    
    
    

activity_main.xml



   

布局文件中可以看到,我们设定的path里面的数据,参考的宽高是100,看看我们的path是怎么写的:

M 50 14 L 90 50 M 10 50 H 90 M 50 86 L 90 50

最终会有一个箭头显示处理,无论我们的SVGPathView宽高如何,都会等比放缩。先看看最后显示的图吧~

SVG显示

为了避免每次都通过解析字符串的方式来生成Path对象,我们需要把ArrayList 转为ArrayList即保存已经解析过的命令,减少重复解析。修改SVGPathView类中的svgStartDataListsvgEndDataList


private ArrayList svgStartDataList;

private ArrayList svgEndDataList;

并在构造函数中,修改svgStartDataListsvgEndDataList对象创建方式:

SVGUtil svgUtil = SVGUtil.getInstance();

ArrayList svgStartStrList = svgUtil.extractSvgData(svgStartPath);
ArrayList svgEndStrList = svgUtil.extractSvgData(svgEndPath);


svgStartDataList = svgUtil.strListToFragList(svgStartStrList);
svgEndDataList = svgUtil.strListToFragList(svgEndStrList);

SVGUtil中添加strListToFragList函数:


public ArrayList strListToFragList(ArrayList svgDataList) {
    ArrayList fragmentPaths = new ArrayList();
    int startIndex = 0;
    Point lastPoint = new Point(0, 0);
    FragmentPath fp = nextFrag(svgDataList, startIndex, lastPoint);
    while (fp != null) {
        fragmentPaths.add(fp);
        switch (fp.pathType) {
        case MOVE:
        case LINE_TO: {
            lastPoint = fp.p1;
            break;
        }
        case CURVE_TO: {
            lastPoint = fp.p3;
            break;
        }
        case QUAD_TO: {
            lastPoint = fp.p2;
            break;
        }

        default:
            break;
        }
        startIndex = startIndex + fp.dataLen + 1;
        fp = nextFrag(svgDataList, startIndex, lastPoint);
    }
    return fragmentPaths;
}

SVGPathView类中的drawPath函数也需要修改,因为我们是通过属性动画动态生成Path了,而不是当初直接解析原始数据生成Path,将drawPath修改如下:

public void drawPath(Path path) {
    clearCanvas();
    mPaint.setStyle(Style.STROKE);
    mPaint.setColor(mPaintColor);

    mCanvas.drawPath(path, mPaint);
    Canvas canvas = surfaceHolder.lockCanvas();
    canvas.drawBitmap(mBitmap, 0, 0, mPaint);
    surfaceHolder.unlockCanvasAndPost(canvas);
}

SVGPathView类中新加一个函数startTransform,用于开启动画,作为开始执行的入口函数:


public void startTransform() {
if (!isAnim) {
    isAnim = true;
    ValueAnimator va = ValueAnimator.ofFloat(0, 1f);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float animatorFactor = (float) animation.getAnimatedValue();
            Path path = SVGUtil.getInstance().parseFragList(
                    svgStartDataList, svgEndDataList, widthFactor,
                    heightFactor, animatorFactor);
            drawPath(path);
        }
    });
    va.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            isAnim = false;
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            isAnim = false;
        }
    });
    va.setDuration(1000).start();

}
}


public void drawPath(Path path) {
clearCanvas();
mPaint.setStyle(Style.STROKE);
mPaint.setColor(mPaintColor);

mCanvas.drawPath(path, mPaint);
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
surfaceHolder.unlockCanvasAndPost(canvas);
}

可以看到,真正的核心函数是SVGUtilparseFragList函数,这个函数是根据起始的Path数据和终止的Path数据,以及动画变化时刻的数据,生成新的Path,这个函数也不复杂:

public Path parseFragList(ArrayList svgStartDataList,
        ArrayList svgEndDataList, float widthFactor,
        float heightFactor, float animatorFactor) {
    Path path = new Path();

    for (int i = 0; i < svgStartDataList.size(); i++) {
        FragmentPath startFp = svgStartDataList.get(i);
        FragmentPath endFp = svgEndDataList.get(i);
        
        int x1 = 0;
        int y1 = 0;
        int x2 = 0;
        int y2 = 0;
        int x3 = 0;
        int y3 = 0;
        if (startFp.p1 != null) {
            x1 = (int) (startFp.p1.x + (endFp.p1.x - startFp.p1.x)
                    * animatorFactor);
            y1 = (int) (startFp.p1.y + (endFp.p1.y - startFp.p1.y)
                    * animatorFactor);
        }

        if (startFp.p2 != null) {
            x2 = (int) (startFp.p2.x + (endFp.p2.x - startFp.p2.x)
                    * animatorFactor);
            y2 = (int) (startFp.p2.y + (endFp.p2.y - startFp.p2.y)
                    * animatorFactor);
        }

        if (startFp.p3 != null) {
            x3 = (int) (startFp.p3.x + (endFp.p3.x - startFp.p3.x)
                    * animatorFactor);
            y3 = (int) (startFp.p3.y + (endFp.p3.y - startFp.p3.y)
                    * animatorFactor);
        }
        switch (startFp.pathType) {
        case MOVE: {

            path.moveTo(x1 * widthFactor, y1 * heightFactor);
            break;
        }
        case LINE_TO: {

            path.lineTo(x1 * widthFactor, y1 * heightFactor);
            break;
        }
        case CURVE_TO: {

            path.cubicTo(x1 * widthFactor, y1 * heightFactor, x2
                    * widthFactor, y2 * heightFactor, x3 * widthFactor, y3
                    * heightFactor);
            break;
        }
        case QUAD_TO: {
            path.quadTo(x1 * widthFactor, y1 * heightFactor, x2
                    * widthFactor, y2 * heightFactor);
            break;
        }
        case CLOSE: {
            path.close();
        }
        default:
            break;
        }
    }
    return path;
}

好啦,看看动画吧~

Path变形
我们再加上旋转动画一起执行,让切换效果更自然一点,先设置rotateDegree属性,并在onAnimationUpdate函数中添加rotateDegree = animatorFactor * 360;注意,需要在drawPath函数执行之前添加。
将drawPath中的

 mCanvas.drawPath(path, mPaint);
mCanvas.save(); 
mCanvas.rotate(rotateDegree, mWidth / 2, mHeight / 2);
mCanvas.drawPath(path, mPaint);

看看效果吧~

旋转切换

动画设置时间为1秒,加上Gif丢帧的原因,所以上面效果看起似乎有点不流畅

最后,请注意,两个变形的Path数据中,对应的命令格式一定要一模一样,否则会出错!!!!
比如,要实现如下效果
加减变形
path数据则必须写成:

   M 10,50 H 90 M 50 10 V 90 
M 10,50 H 90 M 10 50 H 90

虽然减号可以通过如下就可以画出来

M 10,50 H 90 

但是,我们需要加号中后半段数据的最终变形位置,因此不可以省去后面的。

最后献上源码:download.csdn.net/download/hu…