Android之 drawTextOnpath

Android的 Canvas还提供了一个drawTextOnpath ( )方法

package com.test.pathactivity;

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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class PathTextActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_path_text);
        setContentView(new MyTextView(this));
    }

    class MyTextView extends View{

        public static final String DRAW_TEXT = "疯狂Android讲义";
        Path[] mPath = new Path[3];
        Paint mPaint;

        public MyTextView(Context context) {
            super(context);

            mPath[0] = new Path();
            mPath[0].moveTo(0,0);

            for (int i = 0; i < 7; i++) {
                //生成 7个点 随机生成他们的 Y坐标,   并将他们连接成一条 path
                mPath[0].lineTo(i*30, (float) (Math.random()*30));
            }

            mPath[1] = new Path();
            RectF rectF = new RectF(0,0,200,150);
            mPath[1].addOval(rectF,Path.Direction.CCW);

            mPath[2] = new Path();
            mPath[2].addArc(rectF,60,180);

            //初始化画笔
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.BLUE);
            mPaint.setStrokeWidth(5);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);
            canvas.translate(150,50);

            //设置从右边开始绘制 (右对齐)
            mPaint.setTextAlign(Paint.Align.RIGHT);
            mPaint.setTextSize(22);

            //绘制路径
            mPaint.setStyle(Paint.Style.STROKE);
            canvas.drawPath(mPath[0],mPaint);

            //沿着路径绘制一段文本
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawTextOnPath(DRAW_TEXT, mPath[0], -8,20,mPaint);

            //对 canvas 进行坐标转换: 画布下移
            canvas.translate(0,60);

            //绘制路径
            mPaint.setStyle(Paint.Style.STROKE);
            canvas.drawPath(mPath[1],mPaint);

            //沿着路径绘制一段文本
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawTextOnPath(DRAW_TEXT, mPath[1], 20,20,mPaint);

            //对 canvas 进行坐标转换: 画布下移120
            canvas.translate(0,120);

            //绘制路径
            mPaint.setStyle(Paint.Style.STROKE);
            canvas.drawPath(mPath[2],mPaint);

            //沿着路径绘制一段文本
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawTextOnPath(DRAW_TEXT, mPath[2], 10,20,mPaint);

        }
    }
}

你可能感兴趣的:(Android)