Android的Path类是一个非常有用的类,它可以预先在View上将N个点连成一条“路径”,然后调用Canvas的drawPath(path, paint)方法沿着路径绘制图形。实际上Android还为路径绘制提供了PathEffect来定义绘制效果,PathEffect包含了如下子类(每个子类代表一种绘制效果)。
- CornerPathEffect
- DiscretePathEffect
- DashPathEffect
- PathDashPathEffect
- ComposePathEffect
- SumPathEffect
下面程序示范了不使用效果和使用上面6种效果的效果,如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends View{
float phase;
PathEffect[] pathEffects = new PathEffect[7];
int[] colors;
private Paint paint;
Path path;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
//创建并初始化Path
path = new Path();
path.moveTo(0, 0);
for(int i=1; i<=40; i++){
//生成40个点,随机生成他们的Y坐标,并将他们连城一条Path
path.lineTo(i*20, (float)Math.random()*60);
}
//初始化7个一颜色
colors = new int[]{Color.RED, Color.YELLOW, Color.GREEN, Color.BLACK, Color.BLUE, Color.LTGRAY,Color.CYAN};
}
@Override
protected void onDraw(Canvas canvas) {
//将背景填充成白色
canvas.drawColor(Color.WHITE);
//---------------下面开始画7种路径效果------------
pathEffects[0] = null;
pathEffects[1] = new CornerPathEffect(10);
pathEffects[2] = new DiscretePathEffect(3.0f, 5.0f);
pathEffects[3] = new DashPathEffect(new float[]{20, 10, 5, 10}, phase);
Path p = new Path();
p.addRect(0, 0, 8, 8, Path.Direction.CCW);
pathEffects[4] = new PathDashPathEffect(p, 12, phase, PathDashPathEffect.Style.ROTATE);
//初始化ComposePathEffect
pathEffects[5] = new ComposePathEffect(pathEffects[2], pathEffects[4]);
pathEffects[6] = new SumPathEffect(pathEffects[4], pathEffects[3]);
//将画布移动到(8, 8)处开始绘制,后面的操作都以(8,8)作为参照点,默认原点为(0,0)
canvas.translate(80, 80);
//依次使用7种不同的路径效果、7种不同的颜色来绘制
for(int i=0; i<7; i++){
paint.setPathEffect(pathEffects[i]);
paint.setColor(colors[i]);
canvas.drawPath(path, paint);
canvas.translate(0, 200);
}
//改变phase值,形成动画效果
phase += 1;
invalidate();
}
}
}
效果如下:
正如上面的程序中所看到的,当定义DashPathEffect、PathDashEffect时可指定一个phase参数,该参数用于指定路径效果的相位,当该phase参数改变时,绘制效果也略有变化。上面的程序不停地改变phase参数,并不停地重绘该View组件,这将产生动画效果。