Canvas这个类里面的方法类型不多,draw系列和clip系列,下面将写下clipRect()方法的不同参数的使用,以便日后参考。
用法示例
Rect rectA = new Rect(10, 10, 50, 50);
Rect rectB = new Rect(30, 30, 90, 90);
canvas.clipRect(rectA);
canvas.clipRect(rectB, Region.Op.XOR);
Region.Op说明
Op | Meanings |
---|---|
DIFFERENCE | A-B,{e\e∈A ∧ ¬(e∈B)} |
INTERSECT | A ∩ B,{e\e∈A ∧ e∈B} |
REPLACE | {e\e∈B} |
REVERSE_DIFFERENCE | B-A,{e\e∈B ∧ ¬(e∈A)} |
UNION | A ∪ B, {e\e∈A ∨ e∈B} |
XOR | A△B: (A-B)∪(B-A) |
效果图
Demo代码
public class ClipView extends View {
private int mLength;
private Paint mPaint, mTextPaint;
Rect rectOri, rectA, rectB;
int divider = 10;
String sA = "A", sB = "B";
Region.Op[] ops;
int tX, tY;
public ClipView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mTextPaint = new Paint();
mTextPaint.setTextSize(20);
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(Color.BLACK);
rectOri = new Rect();
rectA = new Rect();
rectB = new Rect();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
mLength = (width - 4 * divider) / 3;
rectOri.set(0, 0, mLength, mLength);
rectA.set(10, 10, mLength / 2 + 20, mLength / 2 + 20);
rectB.set(mLength / 2 - 20, mLength / 2 - 20, mLength - 10, mLength - 10);
tX = 10;
tY = mLength - 10;
ops=Region.Op.values();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//draw origin view
canvas.save();
canvas.translate(divider, divider);
mPaint.setColor(Color.WHITE);
canvas.drawRect(rectOri, mPaint);
mPaint.setColor(Color.GREEN);
canvas.drawRect(rectA, mPaint);
mPaint.setColor(Color.RED);
canvas.drawRect(rectB, mPaint);
// draw text
canvas.drawText(sA, rectA.centerX(), rectA.centerY(), mTextPaint);
canvas.drawText(sB, rectB.centerX(), rectB.centerY(), mTextPaint);
canvas.drawText("Origin", tX, tY, mTextPaint);
canvas.restore();
//translate the canvas
canvas.translate(0, mLength + divider);
for (int i = 0; i < 6; i++) {
//draw the compound view
canvas.save();
int dx = divider * (i % 3 + 1) + mLength * (i % 3);
int dy = i > 2 ? (divider * 2 + mLength) : divider;
canvas.translate(dx, dy);
mPaint.setColor(Color.WHITE);
canvas.drawRect(rectOri, mPaint);
//draw text
canvas.drawText(ops[i].name(), tX, tY, mTextPaint);
//do clipping
canvas.clipRect(rectA);
canvas.clipRect(rectB, ops[i]);
//draw all the area
canvas.drawColor(Color.CYAN);
canvas.restore();
}
}
}
Notice:
- 关闭硬件加速,不然部分机型和版本的系统无法正常工作
- 防止overdraw,可以多使用quickReject()和clip相关函数