本节引言:
1.子类作用与构造方法参数分析:
1)CornerPathEffect
CornerPathEffect(float radius)
2)DashPathEffect
DashPathEffect(float[] intervals, float phase)
3)DiscretePathEffect
DiscretePathEffect(float segmentLength, float deviation)
4)PathDashPathEffect
PathDashPathEffect(Path shape, float advance, float phase, PathDashPathEffect.Style style)
5)ComposePathEffect
ComposePathEffect(PathEffect outerpe, PathEffect innerpe)
6)SumPathEffect
SumPathEffect(PathEffect first, PathEffect second)
2.写代码来验证各自的效果
多说无益,写代码最实际,我们写下代码来试试这几个子类各自所起的效果!
运行效果图:
实现代码:
我们自己来写一个View,里面的线移动的效果是phase增加造成的,每次 + 2, 然后invalidate重绘而已,所以别惊讶!PathEffectView.java:
/** * Created by Jay on 2015/10/30 0030. */ public class PathEffectView extends View { private Paint mPaint; private Path mPath; private float phase = 0; private PathEffect[] effects = new PathEffect[7]; private int[] colors; public PathEffectView(Context context) { this(context, null); } public PathEffectView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PathEffectView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //初始化画笔 private void init() { mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); //抗锯齿 mPaint.setStyle(Paint.Style.STROKE); //绘画风格:空心 mPaint.setStrokeWidth(5); //笔触粗细 mPath = new Path(); mPath.moveTo(0, 0); for (int i = 1; i <= 15; i++) { // 生成15个点,随机生成它们的坐标,并将它们连成一条Path mPath.lineTo(i * 40, (float) Math.random() * 100); } // 初始化7个颜色 colors = new int[] { Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW, Color.BLACK, Color.MAGENTA, Color.CYAN }; } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); //初始化其中路径效果: effects[0] = null; //无效果 effects[1] = new CornerPathEffect(10); //CornerPathEffect effects[2] = new DiscretePathEffect(3.0f, 5.0f); //DiscretePathEffect effects[3] = new DashPathEffect(new float[] { 20, 10, 5, 10 },phase); //DashPathEffect Path p = new Path(); p.addRect(0, 0, 8, 8, Path.Direction.CCW); effects[4] = new PathDashPathEffect(p, 12, phase, PathDashPathEffect.Style.ROTATE); //PathDashPathEffect effects[5] = new ComposePathEffect(effects[2], effects[4]); //ComposePathEffect effects[6] = new SumPathEffect(effects[2], effects[4]); //SumPathEffect // 将画布移动到(10,10)处开始绘制 canvas.translate(10, 10); // 依次使用7中不同的路径效果、7中不同的颜色来绘制路径 for (int i = 0; i < effects.length; i++) { mPaint.setPathEffect(effects[i]); mPaint.setColor(colors[i]); canvas.drawPath(mPath, mPaint); canvas.translate(0, 60); } // 改变phase值,形成动画效果 phase += 2; invalidate(); } }
好的,代码的注释已经非常清楚了,这里也不唠叨了~
3.本节示例代码下载:
PathEffectDemo.zip