前面介紹過在Path中添加基本圖形:線段、矩形削锰、圓通铲、貝塞爾曲線,其實(shí)Path還可以進(jìn)行運(yùn)算器贩,多個(gè)Path進(jìn)行圖形運(yùn)算颅夺,得到更加復(fù)雜和不規(guī)則的圖形.
一、運(yùn)算方法
Path類中關(guān)于運(yùn)算的方法
public boolean op(Path path, Op op) {
return op(this, path, op);
}
將當(dāng)前的Path對象和傳入的path對象做運(yùn)算:path.op(path1,op)蛹稍,運(yùn)算結(jié)果保存到當(dāng)前path對象中
public boolean op(Path path1, Path path2, Op op)
將path1吧黄、path2對象做運(yùn)算:path.op(path1,path2,op),運(yùn)算結(jié)果保存到當(dāng)前path對象中
Op :運(yùn)算規(guī)則唆姐,是Path類中的枚舉類拗慨,可選值:
Path.Op.DIFFERENCE
Path.Op.INTERSECT
Path.Op.UNION
Path.Op.XOR
Path.Op.REVERSE_DIFFERENCE
這兩個(gè)運(yùn)算方法需要在API>=19(4.4)以上
二、運(yùn)算規(guī)則
這些運(yùn)算規(guī)則和數(shù)學(xué)中集合的交集厦酬、并集胆描、補(bǔ)集運(yùn)算類似.
下圖中左邊圓代表PathA,右邊圓代表PathB
PathA仗阅、PathB做運(yùn)算:pathA.op(pathB, Op op)
Path.Op.DIFFERENCE
差集:PathA減去與PathB相交的區(qū)域后剩下的區(qū)域(1)
Path.Op.REVERSE_DIFFERENCE
反差集:PathB減去與PathA相交的區(qū)域后剩下的區(qū)域(2)
Path.Op.INTERSECT
交集:PathA與PathB相交的區(qū)域(3)
Path.Op.UNION
并集:PathA與PathB包含的所有區(qū)域(4)
Path.Op.XOR
補(bǔ)集:PathA與PathB包含的所有區(qū)域減去它們相交的區(qū)域后剩下的區(qū)域(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);
}
三昌讲、計(jì)算邊界
public void computeBounds(RectF bounds, boolean exact)
bounds:測量結(jié)果放入矩形bounds中
exact:已經(jīng)不再使用,直接傳入true即可
測試
private void gogogo(Canvas canvas) {
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.BLUE);
RectF rectF = new RectF();// 存放測量結(jié)果的矩形
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并集運(yùn)算
path.computeBounds(rectF, true);// 測量運(yùn)算后的path邊界
canvas.drawPath(path, mPaint);// 繪制path
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.GRAY);
canvas.drawRect(rectF, mPaint);// 繪制邊界
}