Can I draw outside the bounds of an Android Canvas

戏子无情 提交于 2019-11-27 01:43:19
numan salati

To draw outside the bounds, you need to expand the clipRect of the canvas.

Check out the overloaded clipRect methods on the Canvas class.

Note - You will need to specify the Region operation because the default operation is INTERSECT. So something like this:

Rect newRect = canvas.getClipBounds();
newRect.inset(-5, -5)  //make the rect larger

canvas.clipRect (newRect, Region.Op.REPLACE);
//happily draw outside the bound now

try to set

android:clipChildren="false" 

to the parent view

You can draw where you like, but nothing will be saved outside the clipping rectangle.

cesards

The answer @numan gave is almost ok, the problem is memory allocation with that approach, so we should be doing this, instead:

// in constructor/elsewhere
Rect newRect = new Rect();

// in onDraw
canvas.getClipBounds(newRect);
newRect.inset(0, -20);  //make the rect larger
canvas.clipRect(newRect, Region.Op.REPLACE);

That solves the problem :-)

If you want to draw text out of bounds in TextView, you should be doing this instead:

<TextView
    ...
    android:shadowColor="#01000000"
    android:shadowDx="100" // out of right bound
    android:shadowDy="0"
    android:shadowRadius="1"
.../>

It's not working to use clipRect() like @numan's answer because TextView clip it's own rect in onDraw():

if (mShadowRadius != 0) {
    clipLeft += Math.min(0, mShadowDx - mShadowRadius);
    clipRight += Math.max(0, mShadowDx + mShadowRadius);

    clipTop += Math.min(0, mShadowDy - mShadowRadius);
    clipBottom += Math.max(0, mShadowDy + mShadowRadius);
}

canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);

Last but not least, Don't forget to set android:clipChildren="false" and android:clipToPadding="false" in your parent ViewGroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!