在上一篇此类型的文章中是改变偏移量实现动态效果,借助的方法是drawArc,这篇文章依然是改变偏移量,而借助的是PathEffect的子类。 效果图:
private static void makeEffects(PathEffect[] e, float phase) {
e[0] = null; // 无效果
e[1] = new CornerPathEffect(30);//CornerPathEffect
e[2] = new DashPathEffect(new float[] {10, 5, 5, 5}, phase);//DashPathEffect
e[3] = new PathDashPathEffect(makePathDash(), 12, phase,
PathDashPathEffect.Style.ROTATE);//PathDashPathEffect
e[4] = new ComposePathEffect(e[2], e[1]);//ComposePathEffect
e[5] = new ComposePathEffect(e[3], e[1]);//ComposePathEffect
}
实现的效果是上序代码的e[5],使用CornerPathEffect实现圆弧效果,而重点是PathDashPathEffect。
new PathDashPathEffect(makePathDash(), 12, phase,
PathDashPathEffect.Style.ROTATE);
第一个参数为小path图形,案例中博主画的是菱形:
private static Path makePathDash() {
Path p = new Path();
p.moveTo(0, 0);
p.lineTo(4, 4);
p.lineTo(8, 0);
p.lineTo(4, -4);
p.moveTo(0, 0);
return p;
}
第二个参数为每个图形间的间隔。 第三个参数为绘制时的偏离量 第四个参数为样式,博主选择的是ROTATE情:线段连接处的图形转换以旋转到与下一段移动方向相一致的角度进行连接。 最后使用ComposePathEffect进行组合。
private static Path makeFollowPath() {
Path p = new Path();
p.moveTo(0, 0);
p.lineTo(400,0);
p.lineTo(400,400);
p.lineTo(0,400);
p.lineTo(0,0);
return p;
}
mPhase += 1;
invalidate();
public class SampleView extends View {
private Paint mPaint;
private Path mPath;
private PathEffect[] mEffects;
private int mColors;
private float mPhase;
private static void makeEffects(PathEffect[] e, float phase) {
e[0] = null;
e[1] = new CornerPathEffect(30);
e[2] = new DashPathEffect(new float[] {10, 5, 5, 5}, phase);
e[3] = new PathDashPathEffect(makePathDash(), 12, phase,
PathDashPathEffect.Style.ROTATE);
e[4] = new SumPathEffect(e[3], e[1]);
e[5] = new ComposePathEffect(e[3], e[1]);
}
public SampleView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(6);
mPath = makeFollowPath();
//初始化PathEffect[]
mEffects = new PathEffect[6];
mColors = Color.BLACK;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
RectF bounds = new RectF();
mPath.computeBounds(bounds, false);
canvas.translate(10 - bounds.left, 10 - bounds.top);
makeEffects(mEffects, mPhase);
mPhase += 1;
invalidate();
//选择样式
mPaint.setPathEffect(mEffects[5]);
mPaint.setColor(mColors);
canvas.drawPath(mPath, mPaint);
canvas.translate(0, 28);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
mPath = makeFollowPath();
return true;
}
return super.onKeyDown(keyCode, event);
}
//绘制跑动路径
private static Path makeFollowPath() {
Path p = new Path();
p.moveTo(0, 0);
p.lineTo(400,0);
p.lineTo(400,400);
p.lineTo(0,400);
p.lineTo(0,0);
return p;
}
//绘制跑动的小图标
private static Path makePathDash() {
Path p = new Path();
p.moveTo(0, 0);
p.lineTo(4, 4);
p.lineTo(8, 0);
p.lineTo(4, -4);
p.moveTo(0, 0);
return p;
}
}