通常字符串是按水平或者垂直方向显示,现在让字符串welcome按上述弧线显示,如图所示。
在这里通过继承View并覆写onDraw()方法来绘制这个view组件。
绘制的方法onDraw(),主要通过三个类来实现:Canvas(画布) / Paint(画笔) / Path(路径)。
详情参见下面代码:
public class MyTextView extends View {
private static final String TAG ="LinkGame: MyTextView";
private Context context;
public MyTextView(Context context) {
super(context);
Log.d(TAG," MyTextView(Context context)");
this.context = context;
// TODO Auto-generated constructor stub
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Log.d(TAG," MyTextView(Context context, AttributeSet attrs, int defStyleAttr)");
this.context = context;
// TODO Auto-generated constructor stub
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG," MyTextView(Context context, AttributeSet attrs)");
this.context = context;
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Log.d(TAG," onDraw()");
Paint mPaint = new Paint(); //设置画笔
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(3);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(75);
Display display = (Display)((WindowManager) context.getSystemService(context.WINDOW_SERVICE)).getDefaultDisplay();
DisplayMetrics metrice = new DisplayMetrics();
display.getMetrics(metrice);
int windowX = metrice.widthPixels; //获取屏幕宽度和高度
int windowy = metrice.heightPixels;
Log.d(TAG," onDraw() windowX = "+ windowX + " windowy = "+windowy);
Path mArcPath = new Path(); //绘制圆弧
RectF mRectF = new RectF(0,windowy*1/20,windowX*7/8,windowy*2/5); mArcPath.addArc(mRectF, -140, 55);
canvas.drawTextOnPath(context.getString(R.string.welcome), mArcPath, 0, 0, mPaint); //让文字随着圆弧显示
//mPaint.setColor(Color.BLACK);
//mPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(mArcPath, mPaint);
//canvas.drawRect(mRectF, mPaint);
}
}
其中最主要的方法就是Canvas类中的:drawTextOnPath(text, path, hOffset, vOffset, paint)
text是要显示的字符串,path是所绘制的路径,hOffset是水平角度的偏移,vOffset是垂直角度的偏移,paint是画笔。
还有一点需要注意的是,构造方法MyTextView(),需要继承实现父类的三个构造方法。否则会出现编译错误。