前面介绍过在Path中添加基本图形:线段、矩形、圆、贝塞尔曲线,其实Path还可以进行运算,多个Path进行图形运算,得到更加复杂和不规则的图形.
一、运算方法
Path类中关于运算的方法
public boolean op(Path path, Op op) {
return op(this, path, op);
}
将当前的Path对象和传入的path对象做运算:path.op(path1,op),运算结果保存到当前path对象中
public boolean op(Path path1, Path path2, Op op)
将path1、path2对象做运算:path.op(path1,path2,op),运算结果保存到当前path对象中
Op :运算规则,是Path类中的枚举类,可选值:
Path.Op.DIFFERENCE
Path.Op.INTERSECT
Path.Op.UNION
Path.Op.XOR
Path.Op.REVERSE_DIFFERENCE
这两个运算方法需要在API>=19(4.4)以上
二、运算规则
这些运算规则和数学中集合的交集、并集、补集运算类似.
下图中左边圆代表PathA,右边圆代表PathB
PathA、PathB做运算:pathA.op(pathB, Op op)
Path.Op.DIFFERENCE
差集:PathA减去与PathB相交的区域后剩下的区域(1)
Path.Op.REVERSE_DIFFERENCE
反差集:PathB减去与PathA相交的区域后剩下的区域(2)
Path.Op.INTERSECT
交集:PathA与PathB相交的区域(3)
Path.Op.UNION
并集:PathA与PathB包含的所有区域(4)
Path.Op.XOR
补集:PathA与PathB包含的所有区域减去它们相交的区域后剩下的区域(5)
测试
private void gogogo(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
// mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.BLUE);
Path path = new Path();
Path path1 = new Path();
path.addCircle(200, 200, 100, Path.Direction.CW);
path1.addCircle(280, 200, 100, Path.Direction.CW);
// path.op(path1, Path.Op.DIFFERENCE);
// path.op(path1, Path.Op.REVERSE_DIFFERENCE);
// path.op(path1, Path.Op.INTERSECT);
// path.op(path1, Path.Op.UNION);
// path.op(path1, Path.Op.XOR);
canvas.drawPath(path, mPaint);
}
三、计算边界
public void computeBounds(RectF bounds, boolean exact)
bounds:测量结果放入矩形bounds中
exact:已经不再使用,直接传入true即可
测试
private void gogogo(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.BLUE);
RectF rectF = new RectF();// 存放测量结果的矩形
Path path = new Path();
Path path1 = new Path();
path.addCircle(200, 200, 100, Path.Direction.CW);
path1.addCircle(280, 200, 100, Path.Direction.CW);
path.op(path1, Path.Op.UNION);// path、path1并集运算
path.computeBounds(rectF, true);// 测量运算后的path边界
canvas.drawPath(path, mPaint);// 绘制path
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.GRAY);
canvas.drawRect(rectF, mPaint);// 绘制边界
}