36

I'm porting an app written in a graphics environment that allows drawing to happen outside the bounds of the clipping rectangle. Any way to do this in Android?

Mark
  • 1,019
  • 4
  • 12
  • 14

6 Answers6

50

try to set

android:clipChildren="false" 

to the parent view

Danylo.Vus
  • 919
  • 9
  • 11
47

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
uthark
  • 5,233
  • 2
  • 43
  • 58
numan salati
  • 19,196
  • 9
  • 60
  • 66
9

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

CaseyB
  • 24,495
  • 12
  • 73
  • 109
3

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 :-)

Tom
  • 6,110
  • 1
  • 40
  • 59
cesards
  • 15,172
  • 11
  • 66
  • 65
2

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

legendmohe
  • 711
  • 7
  • 10
  • [SOLVED] WOKED! ((ViewGroup) parent).setClipChildren(true); ((ViewGroup) parent).setClipToPadding(true); solved for my using this when I needed to draw over the other views at same hierarchy thx ! – Arthur Melo Feb 28 '19 at 22:07
0

If what you want is just draw outside the view bounds (programmatically), cut the long story short.

parentLayout.setClipChildren(false);

or via xml :

 android:clipChildren="false"

enter image description here

ucMedia
  • 3,221
  • 4
  • 32
  • 42