How setbounds of drawable works in Android?

Wai Yan Hein picture Wai Yan Hein · Apr 19, 2016 · Viewed 18.2k times · Source

I am confused with setbounds method of drawable in Android. I know it is used with drawable and it set where drawable and how large it is. Briefly, it defines, bounding rectangle for drawable. But I am confused: does it set border or padding or its width or height?

This is how we use setbounds

drawableInstance.setBounds(L,T,R,B);

First scenario

So in above case, If I set 5,5,5,5 for L,T,R,B respectively, L,T,R,B of drawable will be always from its parent respectively? I mean will it be like setting hidden 5px border to every side?Besides, if image is not large enough to meets that border width to its parent, will image be bigger?

Second scenario

I set 5,5,100,100 for L,T,R,B respectively. What I am confusing is, it will starts drawing from away from parent 5px to the top and 5px to the left. That will be the start point. Then image with will be 100px because I set 100 for right. So it goes to the right 100px. Same to bottom with right.

But I tested it. I think both is not as what I think. How does it work, especially in relation to each parameter of setBounds?

Answer

Mike M. picture Mike M. · Apr 19, 2016

The bounds values are absolute, not relative. That is, width == right - left, and height == bottom - top.

Your first example will have the top left corner of the Drawable at (5, 5), but the width and height will both be 0.

The second example will also have the top left corner at (5, 5), and the width and height will both be 95.

The bounds are not dependent on the dimensions of the Canvas to which the Drawable is drawn. For instance, if you draw a Drawable with the bounds of your second example onto a View that is only 50 by 50, its left and top sides will be inset by 5, but it will get cut off at the right and bottom borders.