# canvas的一些有用的使用小结

1259人阅读 评论(0)

## 4.canvas.translate 方法：

 int w = getWidth();
int h = getHeight();
Paint p = new Paint();
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(w / 2, h / 2, 150, p);
p.setColor(Color.WHITE);
canvas.drawCircle(w / 2, h / 2, 140, p);
p.setColor(Color.BLACK);
p.setStrokeWidth(4);
for (int i = 0; i < 12; i++) {
canvas.drawLine(w / 2 - 140, h / 2, w / 2 - 130, h / 2, p);
canvas.rotate(360 / 12, w / 2, h / 2);
}

canvas.save();
canvas.translate(w / 2, h / 2);
canvas.drawLine(0, 0, 20, 0, p);
canvas.drawLine(0,0,0,50,p);
canvas.restore();

## 4.结合Matrix的使用

Matrix的对图像的处理可分为四类基本变换：

Translate 平移变换

Rotate 旋转变换

Scale 缩放变换

Skew 错切变换

## 5.canvas.clipRect

canvas裁剪：有6种裁剪，分别是：

Region.Op.DIFFERENCE   显示裁剪区以外的部分

<pre name="code" class="java">canvas.drawColor(Color.GRAY);
Paint p=new Paint();
canvas.clipRect(50, 50, 200, 300, Region.Op.DIFFERENCE       );
p.setAntiAlias(true);
Rect rect=new Rect();
rect.set(50, 50, 200, 400);
p.setColor(Color.RED);
canvas.drawRect(rect, p);
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 150, p);


Region.Op.REPLACE     是显示裁剪区以内的部分

<pre name="code" class="java"> canvas.clipRect(50, 50, 200, 300, Region.Op.REPLACE  );
p.setAntiAlias(true);
Rect rect=new Rect();
rect.set(50, 50, 200, 400);
p.setColor(Color.RED);
canvas.drawRect(rect, p);
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 150, p);


Region.Op.REVERSE_DIFFERENCE   两次裁剪区域的的差集部分：
 Paint p=new Paint();
canvas.clipRect(50, 50, 200, 300, Region.Op.REVERSE_DIFFERENCE  );
canvas.clipRect(50, 50, 100, 200, Region.Op.REVERSE_DIFFERENCE  );
p.setAntiAlias(true);
Rect rect=new Rect();
rect.set(50, 50, 200, 400);
p.setColor(Color.RED);
canvas.drawRect(rect, p);
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 150, p);

Region.Op.INTERSECT   两次裁剪区域的交集部分：

<pre name="code" class="java">canvas.drawColor(Color.GRAY);
Paint p=new Paint();
canvas.clipRect(50, 50, 200, 300, Region.Op.INTERSECT      );
canvas.clipRect(50, 50, 100, 200, Region.Op.INTERSECT        );
p.setAntiAlias(true);
Rect rect=new Rect();
rect.set(50, 50, 200, 400);
p.setColor(Color.RED);
canvas.drawRect(rect, p);
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 150, p);


Region.Op.UNION  两次裁剪的并集

Region.Op.XOR  补集 就是全集的减去交集生育部分显示

## 6.canvas.clipPath 方法：

Bitmap b= BitmapFactory.decodeResource(getResources(), R.mipmap.pic);
canvas.drawColor(Color.GRAY);
Paint p=new Paint();
Path path = new Path();
canvas.clipPath(path,Region.Op.INTERSECT);

p.setAntiAlias(true);
Rect rect=new Rect();
rect.set(50, 50, 200, 400);
p.setColor(Color.RED);
canvas.drawRect(rect, p);
p.setColor(Color.parseColor("#00bcd4"));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 150, p);

0
0

个人资料
• 访问：104297次
• 积分：2138
• 等级：
• 排名：千里之外
• 原创：113篇
• 转载：20篇
• 译文：0篇
• 评论：107条
最新评论