1.代码及解释如下:
public class Main3Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
setContentView(layout);
MyPathView view = new MyPathView(this);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.addView(view);
}
class MyPathView extends View {
final String DRAW_STR = "你好啊!";
Path[] paths = new Path[3];
Paint paint;
public MyPathView(Context context) {
super(context);
paths[0] = new Path();
paths[0].moveTo(0, 0);
for (int i = 1; i <= 20; i++) {
paths[0].lineTo(i * 30, (float) (Math.random() * 30)); //随机20个点连成路径
}
paths[1] = new Path();
RectF rectF = new RectF(0, 0, 600, 300);
paths[1].addOval(rectF, Path.Direction.CCW); //在矩形范围中加一个椭圆路径
paths[2] = new Path();
paths[2].addArc(rectF, 60, 180); //画弧线,从60度角开始画了滑过180度
//初始化画笔
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setStrokeWidth(2);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.translate(40 ,40);
paint.setTextAlign(Paint.Align.RIGHT); //设置文本在路径中是左对齐还是右对齐还是居中
paint.setTextSize(20);
paint.setStyle(Paint.Style.STROKE); //绘制线条还是用stroke
canvas.drawPath(paths[0] , paint); //绘制第一个路径
paint.setTextSize(60);
paint.setStyle(Paint.Style.FILL); //绘制文本还是用fill
//第3,4参数分别为文本在路径上的位置的偏移量
//原本文本在路径的上方,然后y轴偏移了30,这样路径就穿过了文字,文字不在路径上方了。
canvas.drawTextOnPath(DRAW_STR , paths[0] , 0 , 30 , paint); //在第一个路径上绘制文本
canvas.translate(0,60);
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[1] , paint); //绘制第二个路径
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath(DRAW_STR , paths[1] , 0 , 30 , paint);//在第2个路径上绘制文本
canvas.translate(0 , 360);
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[2] , paint); //绘制第3个路径
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath(DRAW_STR , paths[2] , 0 , 30 , paint);//在第3个路径上绘制文本
}
}
}
2.效果如下: