开发者

Fill canvas outside rectangle

开发者 https://www.devze.com 2023-02-11 13:52 出处:网络
I want to fill the area outside a rectangle on a canvas. I use canvas.drawRect(pTopLeft.x, pTopLeft.y, pBotRight.x, pBotRight.y, paint);

I want to fill the area outside a rectangle on a canvas. I use

 canvas.drawRect(pTopLeft.x, pTopLeft.y, pBotRight.x, pBotRight.y, paint);

to draw the rec开发者_如何学编程tangle, but can't figure out how to fill outside the rectangle/clip.

Thanks Geoff


Thanks ted and trojanfoe - the neatest solution I've come up with is

    Point pTopLeft = new Point();
    Point pBotRight = new Point();

    //TODO:set x,y for points

    Rect rHole = new Rect(pTopLeft.x, pTopLeft.y, pBotRight.x, pBotRight.y);
    //assume current clip is full canvas
    //put a hole in the current clip
    canvas.clipRect(rHole,  Region.Op.DIFFERENCE);
    //fill with semi-transparent red
    canvas.drawARGB(50, 255, 0, 0);
    //restore full canvas clip for any subsequent operations
    canvas.clipRect(new Rect(0, 0, canvas.getWidth(), canvas.getHeight())
                    , Region.Op.REPLACE);


You aren't going to fill outside the clip; that's the kind of thing clip is there to prevent! If you want to fill the space outside a rect and inside the drawing layer bounds, construct four auxiliary rects:

Rect above = new Rect(0, 0, canvas.getWidth(), pTopLeft.y);
Rect left = new Rect(0, pTopLeft.y, pTopLeft.x, pBotRight.y);
Rect right = new Rect(pBotRight.x, pTopLeft.y, canvas.getWidth(), pBotRight.y);
Rect bottom = new Rect(0, pBotRight.y, canvas.getWidth(), canvas.getHeight());

Then fill these.


ICS and above ...

canvas.clipRect(rHole,  Region.Op.DIFFERENCE);

XOR, Difference and ReverseDifference clip modes are ignored by ICS if hardware acceleration is enabled.

Just disable 2D hardware acceleration in your view:

myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Reference Android: Howto use clipRect in API15


You can't draw outside of the Canvas; that area belongs to the parent View. Do you have the ability to subclass the parent View and do your drawing in that class instead?

If you want to draw outside of the Canvas clip then you'll have to invalidate() the areas you are interested in.

0

精彩评论

暂无评论...
验证码 换一张
取 消