效果图:
103127256831351815.png基础知识:
在Android中的绘图应该继承View组件,并重写它的onDraw(Canvas canvas)方法,Canvas代表了“依附”于指定View的画布,它提供了如下方法绘制各种图形(Canvas提供了一个drawTextOnPath(String text,Path path,float hOffset,float vOffset,Paint paint)方法,该方法可以沿着Path路径绘制文本,其中text指文本内容,hOffset参数指定水平偏移、vOffset指定垂直偏移):
20130628234754046.pngCanvas提供的绘制方法中用到了一个API:Paint,Paint 代表了Canvas上的画笔,主要用于绘制风格,包括画笔颜色、画笔笔触粗细、填充风格等。它提供了如下方法:
20130628235246203.pngpackage com.example.h.drawtextonpathproject;
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.util.AttributeSet;
import android.view.View;
/**
* 作者:huangchen on 2016/6/24 10:17
*/
public class CustomPathView extends View {
private final String DEFAULT_TEXT = "让 购 物 便 捷";
private Paint paint;
private Path[] paths = new Path[3];
public CustomPathView(Context context) {
super(context);
initView();
}
public CustomPathView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public CustomPathView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setStrokeWidth(4);
paths[0] = new Path();
paths[0].moveTo(0, 0);
for (int i = 0; i < DEFAULT_TEXT.length(); i++) {
//生成6个点,随机生成Y坐标,并且连在一起
paths[0].lineTo(i * 30, (float) (Math.random() * 30));
}
paths[1] = new Path();
RectF oval = new RectF(0, 0, 400, 200);
paths[1].addOval(oval, Path.Direction.CCW);//椭圆路径
paths[2] = new Path();
paths[2].addArc(oval, 60, 180);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//背景白色
canvas.drawColor(Color.WHITE);
canvas.translate(240, 80);
//右边开始绘制,对齐
paint.setTextAlign(Paint.Align.RIGHT);
paint.setTextSize(40);
/* //绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[0], paint);*/
//绘制文字
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath(DEFAULT_TEXT, paths[0], -8, 10, paint);
//下移
canvas.translate(0, 150);
//绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[1], paint);
//绘制文字
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath(DEFAULT_TEXT, paths[1], -20, -20, paint);
//下移
canvas.translate(0, 300);
//绘制路径
paint.setStyle(Paint.Style.STROKE);
canvas.drawPath(paths[2], paint);
//绘制文字
paint.setStyle(Paint.Style.FILL);
canvas.drawTextOnPath(DEFAULT_TEXT, paths[2], -10, -20, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
}
结语:
本文主要讲了自定义view的简单使用,主要使用了canvas.drawTextOnPath方法来对文字围绕一定的轨迹显示,虽然只是简单的实现,但是如何复杂的效果都是基于一步步简单的效果堆积出来的,最重要的是理解原理,知其然知其所以然才是最重要的。
项目地址:https://github.com/ruanjiankeji/DrawTextOnPathProject
有问题可以随时指正,相互学习。
网友评论