Canvas中用drawPoint方法绘制点,代码如下所示:
private void drawPoint(Canvas canvas){ int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int x = canvasWidth / 2; int deltaY = canvasHeight / 3; int y = deltaY / 2; paint.setColor(0xff8bc5ba);//设置颜色 paint.setStrokeWidth(50 * density);//设置线宽,如果不设置线宽,无法绘制点 //绘制Cap为BUTT的点 paint.setStrokeCap(Paint.Cap.BUTT); canvas.drawPoint(x, y, paint); //绘制Cap为ROUND的点 canvas.translate(0, deltaY); paint.setStrokeCap(Paint.Cap.ROUND); canvas.drawPoint(x, y, paint); //绘制Cap为SQUARE的点 canvas.translate(0, deltaY); paint.setStrokeCap(Paint.Cap.SQUARE); canvas.drawPoint(x, y, paint); }界面如下所示:
下面对以上代码进行说明:
drawLineCanvas通过drawLine方法绘制一条线段,通过drawLines方法绘制多段线,使用代码如下所示:
下面对以上代码进行说明:
当用BUTT作为帽端时,所绘制的线段恰好在起点终点位置处戛然而止,两端是方形,上图中第一条加粗的线段就是用BUTT作为帽端绘制的。
当用ROUND作为帽端时,所绘制的线段的两端端点会超出起点和终点一点距离,并且两端是圆形状,上图中第二条加粗的线段就是用ROUND作为帽端绘制的。
当用SQUARE作为帽端时,所绘制的线段的两端端点也会超出起点和终点一点距离,两端点的形状是方形,上图中最后一条加粗的线段就是用SQUARE作为帽端绘制的。
Canvas通过drawRect方法绘制矩形,使用代码如下所示:
private void drawRect(Canvas canvas){ int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); //默认画笔的填充色是黑色 int left1 = 10; int top1 = 10; int right1 = canvasWidth / 3; int bottom1 = canvasHeight /3; canvas.drawRect(left1, top1, right1, bottom1, paint); //修改画笔颜色 paint.setColor(0xff8bc5ba);//A:ff,R:8b,G:c5,B:ba int left2 = canvasWidth / 3 * 2; int top2 = 10; int right2 = canvasWidth - 10; int bottom2 = canvasHeight / 3; canvas.drawRect(left2, top2, right2, bottom2, paint); }界面如下所示:
其方法签名是drawRect(float left, float top, float right, float bottom, Paint paint),left和right表示矩形的左边和右边分别到绘图坐标系y轴正半轴的距离,top和bottom表示矩形的上边和下边分别到绘图坐标系x轴正半轴的距离。
drawCircleCanvas中用drawCircle方法绘制圆形,使用代码如下所示:
private void drawCircle(Canvas canvas){ paint.setColor(0xff8bc5ba);//设置颜色 paint.setStyle(Paint.Style.FILL);//默认绘图为填充模式 int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int halfCanvasWidth = canvasWidth / 2; int count = 3; int D = canvasHeight / (count + 1); int R = D / 2; //绘制圆 canvas.translate(0, D / (count + 1)); canvas.drawCircle(halfCanvasWidth, R, R, paint); //通过绘制两个圆形成圆环 //1. 首先绘制大圆 canvas.translate(0, D + D / (count + 1)); canvas.drawCircle(halfCanvasWidth, R, R, paint); //2. 然后绘制小圆,让小圆覆盖大圆,形成圆环效果 int r = (int)(R * 0.75); paint.setColor(0xffffffff);//将画笔设置为白色,画小圆 canvas.drawCircle(halfCanvasWidth, R, r, paint); //通过线条绘图模式绘制圆环 canvas.translate(0, D + D / (count + 1)); paint.setColor(0xff8bc5ba);//设置颜色 paint.setStyle(Paint.Style.STROKE);//绘图为线条模式 float strokeWidth = (float)(R * 0.25); paint.setStrokeWidth(strokeWidth); canvas.drawCircle(halfCanvasWidth, R, R, paint); }界面如下所示: