android 绘图之Canvas,Paint类

Canvas,Paint

1.在android 绘图但中经常要用到Canvas和Paint类,Canvas好比是一张画布,上面已经有你想绘制图画的轮廓了,而Paint就好比是画笔,就要给Canvas进行添色等操作。

这两个类通常都是在onDraw(Canvas canvas)方法中用的。

2.Bitmap:代表一张位图,BitmapDrawable里封装的突变就是一个Bitmao对象

3.Canvas里面有一些例如:

drawArc(参数) 绘制弧

drawBitmao(Bitmap bitmap ,Rect rect,Rect dst,Paint paint)  在指定点绘制从源图中"挖取"的一块

clipRect(float left,float top,float right,float bottom)  剪切一个矩形区域

clipRegion(Region region)  剪切一个指定区域。

Canvas除了直接绘制一个基本图形外,还提供了如下方法进行坐标变化:

rotate(float degree,float px, float py):对Canvas执行旋转变化

scale(float sx,float sy,float px,float py):对Cnavas进行缩放变换

skew(float sx,float sy):对Canvas执行倾斜变换

translate(float dx,float dy):对Cnavas执行移动

4.Paint类主要用于设置绘制风格包括画笔颜色,画笔粗细,填充风格等,

Paint提供了一些方法

setARGB(int a,int r,int g,int b)/setColor(int color)  :设置颜色

等一些方法

5.下面通过一个例子来说明一下这两个类:

 1 public class MyView extends View {
 2 
 3     public MyView(Context context) {
 4         super(context);
 5         // TODO Auto-generated constructor stub
 6     }
 7 
 8     public MyView(Context context, AttributeSet attrs) {
 9         super(context, attrs);
10         // TODO Auto-generated constructor stub
11     }
12 
13     public MyView(Context context, AttributeSet attrs, int defStyle) {
14         super(context, attrs, defStyle);
15         // TODO Auto-generated constructor stub
16     }
17 
18     // 重写该方法,进行绘图
19     @Override
20     protected void onDraw(Canvas canvas) {
21         super.onDraw(canvas);
22         // 整张画布绘制成白色
23         canvas.drawColor(Color.WHITE);
24         Paint paint = new Paint();
25         // 去锯齿
26         paint.setAntiAlias(true);
27         paint.setColor(Color.BLUE);
28         paint.setStyle(Style.STROKE);
29         paint.setStrokeWidth(3);
30         // 绘制图形
31         canvas.drawCircle(40, 40, 30, paint);
32         // 绘制正方型
33         canvas.drawRect(10, 80, 70, 140, paint);
34         // 绘制矩形
35         canvas.drawRect(10, 150, 70, 190, paint);
36         RectF rel = new RectF(10, 200, 70, 230);
37         // 绘制圆角矩形
38         canvas.drawRoundRect(rel, 15, 15, paint);
39         RectF rell = new RectF(10, 240, 70, 270);
40         // 绘制椭圆
41         canvas.drawOval(rell, paint);
42         // 定义一个Path对象,封闭成一个三角形
43         Path path1 = new Path();
44         path1.moveTo(10, 340);
45         path1.lineTo(70, 340);
46         path1.lineTo(40, 290);
47         path1.close();
48 
49     }
50 
51 }
原文地址:https://www.cnblogs.com/liangstudyhome/p/3855722.html