Android ApiDemos示例解析(76):Graphics->Regions
二维图形之间可以通过“加”,“减”,“交”,“异或”等逻辑运算构成新的图形。
本例使用了两个矩形通过“加”,“减”,“交”,“异或”构成组合后的图像,Region除支持矩形外,还可以使用Path来定义一个任意区域,然后再组合成复杂形状。可以参见Android简明开发教程十四:Context Menu 绘制几何图形 “梨子”。
[java]
canvas.save();
canvas.translate(0, 140);
drawRgn(canvas, Color.RED, "Union", Region.Op.UNION);
canvas.restore();
canvas.save();
canvas.translate(0, 280);
drawRgn(canvas, Color.BLUE, "Xor", Region.Op.XOR);
canvas.restore();
canvas.save();
canvas.translate(160, 140);
drawRgn(canvas, Color.GREEN, "Difference", Region.Op.DIFFERENCE);
canvas.restore();
canvas.save();
canvas.translate(160, 280);
drawRgn(canvas, Color.WHITE, "Intersect", Region.Op.INTERSECT);
canvas.restore();
...
private void drawRgn(Canvas canvas, int color,
String str, Region.Op op) {
if (str != null) {
mPaint.setColor(Color.BLACK);
canvas.drawText(str, 80, 24, mPaint);
}
Region rgn = new Region();
rgn.set(mRect1);
rgn.op(mRect2, op);
mPaint.setColor(color);
RegionIterator iter = new RegionIterator(rgn);
Rect r = new Rect();
canvas.translate(0, 30);
mPaint.setColor(color);
while (iter.next(r)) {
canvas.drawRect(r, mPaint);
}
drawOriginalRects(canvas, 0x80);
}
canvas.save();
canvas.translate(0, 140);
drawRgn(canvas, Color.RED, "Union", Region.Op.UNION);
canvas.restore();
canvas.save();
canvas.translate(0, 280);
drawRgn(canvas, Color.BLUE, "Xor", Region.Op.XOR);
canvas.restore();
canvas.save();
canvas.translate(160, 140);
drawRgn(canvas, Color.GREEN, "Difference", Region.Op.DIFFERENCE);
canvas.restore();
canvas.save();
canvas.translate(160, 280);
drawRgn(canvas, Color.WHITE, "Intersect", Region.Op.INTERSECT);
canvas.restore();
...
private void drawRgn(Canvas canvas, int color,
String str, Region.Op op) {
if (str != null) {
mPaint.setColor(Color.BLACK);
canvas.drawText(str, 80, 24, mPaint);
}
Region rgn = new Region();
rgn.set(mRect1);
rgn.op(mRect2, op);
mPaint.setColor(color);
RegionIterator iter = new RegionIterator(rgn);
Rect r = new Rect();
canvas.translate(0, 30);
mPaint.setColor(color);
while (iter.next(r)) {
canvas.drawRect(r, mPaint);
}
drawOriginalRects(canvas, 0x80);
}
作者:mapdigit
补充:移动开发 , Android ,