/*这个demon演示了Region的不同的组合方式。 组合即当前的Region和另外的一个Region组合,可以用不同的Op方式来进行组合。
Op是一个枚举,定义在Region类中。
假设用region1 去组合region2
public enum Op {
DIFFERENCE(0), //最终区域为region1 与 region2不同的区域
INTERSECT(1), // 最终区域为region1 与 region2相交的区域
UNION(2), //最终区域为region1 与 region2组合一起的区域
XOR(3), //最终区域为region1 与 region2相交之外的区域
REVERSE_DIFFERENCE(4), //最终区域为region2 与 region1不同的区域
REPLACE(5); //最终区域为为region2的区域
}
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private class SampleView extends View{
private Paint mPaint=new Paint();
private Rect mRect1=new Rect();
private Rect mRect2=new Rect();
public SampleView(Context context) {
super(context);
setFocusable(true);
mPaint.setAntiAlias(true);
mPaint.setTextSize(16);
mPaint.setTextAlign(Paint.Align.CENTER);
mRect1.set(10, 10, 100, 80);
mRect2.set(50, 50, 130, 110);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GRAY);
canvas.save();
canvas.translate(80, 5);
//绘制原始图形
drawOrginalRects(canvas,0xff);
canvas.restore();
canvas.save();
canvas.translate(0, 120);
//绘制组合在一起的区域
drawRgn(canvas,Color.RED,"union",Region.Op.UNION);
canvas.restore();
canvas.save();
canvas.translate(160, 120);
//绘制组合在一起的区域
drawRgn(canvas,Color.BLUE,"Xor",Region.Op.XOR);
canvas.restore();
canvas.save();
canvas.translate(0, 260);
//绘制组合在一起的区域
drawRgn(canvas,Color.GREEN,"Difference",Region.Op.DIFFERENCE);
canvas.restore();
canvas.save();
canvas.translate(160, 260);
//绘制组合在一起的区域
drawRgn(canvas,Color.WHITE,"union",Region.Op.INTERSECT);
canvas.restore();
}
private void drawRgn(Canvas canvas, int color, String str, 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);
while(iter.next(r)){
//迭代所有的rect并绘制
canvas.drawRect(r, mPaint);
}
drawOrginalRects(canvas, 0x88);
}
private void drawOrginalRects(Canvas canvas, int alpha) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.RED);
mPaint.setAlpha(alpha);
drawCentered(canvas,mRect1,mPaint);
mPaint.setColor(Color.BLUE);
mPaint.setAlpha(alpha);
drawCentered(canvas,mRect2,mPaint);
//canvas.drawRect(mRect2, mPaint);
mPaint.setStyle(Paint.Style.FILL);
}
//将外边框的宽度设置为0.5个像素
private void drawCentered(Canvas canvas, Rect r, Paint p) {
float inset=p.getStrokeWidth()*0.5f;
if(inset==0){
inset=0.5f;
}
canvas.drawRect(r.left+inset, r.top+inset, r.right-inset, r.bottom-inset, p);
}
}
}
11-03