Android的Canvas还提供了一个
drawTextOnPath(String text,Path path,float hOffset,float vOffset,Paint paint)
该方法沿着Path绘制文本,hOffset参数指定水平偏移,vOffset参数指定垂直偏移
MainActivity.java
package com.example.drawpathtext;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyTextView(MainActivity.this));
}
class MyTextView extends View{
Path[] paths=new Path[3];
Paint paint;
public MyTextView(Context context) {
super(context);
paths[0]=new Path();
paths[0].moveTo(0, 0);
for(int i=1;i<=7;i++){
//生成7个点,随机生成他们的Y坐标,并将他们连成一条线
paths[0].lineTo(i*30, (float) (Math.random()*30));
}
paths[1]=new Path();
RectF rectF=new RectF(0,0,200,120);
//向路径中添加椭圆
paths[1].addOval(rectF, Path.Direction.CCW);
paths[2]=new Path();
//向路径中添加椭圆弧,60代表开始角度,180代表弧线扫描过的角度
paths[2].addArc(rectF, 60, 180);
//初始化画笔
paint=new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.GRAY);
paint.setStrokeWidth(2);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.translate(40, 40);
//设置从右边开始绘制
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(20);
//绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[0], paint);
//沿着路径绘制一段文本
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath("安卓手机开发", paths[0], 0, 10, paint);
canvas.translate(0, 60);
//绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[1], paint);
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath("安卓手机开发", paths[1], 0, 10, paint);
canvas.translate(0, 120);
//绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[2], paint);
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath("安卓手机开发", paths[2], 5, 5, paint);
}
}
}