Canvas(画布),Paint(画笔),Path(路径)。这三个是常用的绘图工具,是自定义View的基本。
效果图如下:
自定义View的代码如下:
package com.deepreality.canvasandpaintandpath; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class MyView extends View { private Paint mPaint;//定义一个画笔 public MyView(Context context) { super(context); paintInit(); } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); paintInit(); } public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); paintInit(); } private void paintInit() { mPaint = new Paint(); mPaint.setAntiAlias(true); //抗锯齿 mPaint.setColor(getResources().getColor(R.color.colorAccent));//画笔颜色 mPaint.setStyle(Paint.Style.FILL); //画笔风格 mPaint.setTextSize(36); //绘制文字大小,单位px mPaint.setStrokeWidth(5); //画笔粗细 } private Path pathInit() { Path path = new Path(); //不会进行绘制,只用于移动移动画笔 path.moveTo(10, 10); //用于直线绘制,默认从(0,0)开始绘制,用moveTo移动 path.lineTo(100, 50); path.lineTo(200,40); path.lineTo(300, 20); path.lineTo(200, 10); path.lineTo(100, 70); path.lineTo(50, 40); path.close(); return path; } private Path pathInit1() { Path path = new Path(); path.moveTo(40, 40); path.lineTo(100, 100); path.lineTo(200, 200); path.lineTo(300, 300); path.close(); return path; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //设置画布背景颜色 //canvas.drawColor(getResources().getColor(R.color.colorYellow)); //画实心圆 //绘制圆,参数一是中心点的x轴,参数二是中心点的y轴,参数三是半径,参数四是paint对象; canvas.drawCircle(200, 200, 100, mPaint); //画矩形 //canvas.drawRect(100, 100, 300, 300, mPaint); //绘制bitmap //canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.meizi), 0, 0, mPaint); //绘制弧形区域 //参数一是RectF对象,一个矩形区域椭圆形的界限用于定义在形状、大小、电弧,参数二是起始角 (度)在电弧的开始,参数三扫描角(度)开始顺时针测量的,参数四是如果这是真的话,包括椭圆中心的电 弧,并关闭它,如果它是假这将是一个弧线,参数五是Paint对象; //canvas.drawArc(new RectF(0, 0, 200, 200),0,90,true, mPaint); //画圆角矩形 //canvas.drawRoundRect(new RectF(10, 10, 210, 110), 15, 15, mPaint); //画椭圆 //canvas.drawOval(new RectF(0,0,200,300),mPaint); //绘制多边形 //Path path = pathInit(); //canvas.drawPath(path, mPaint); //绘制文字 //canvas.drawText("这是一段Canvas(画布)绘制的文字",50,50, mPaint); //Path path = pathInit1(); //canvas.drawTextOnPath("这是一段根据设计路径(Path)绘制的文字", path, 40, 40, mPaint); } }