I'm making an app where I use UIEdgeInsetsMake
for resizableImageWithCapInsets
, but I don't understand how does it works exactly, UIEdgeInsetsMake
has 4 arguments:
But they're floats so I don't know how to set that to an image, thanks! :D
According to the documentation:
You use this method to add cap insets to an image or to change the existing cap insets of an image. In both cases, you get back a new image and the original image remains untouched.
During scaling or resizing of the image, areas covered by a cap are not scaled or resized. Instead, the pixel area not covered by the cap in each direction is tiled, left-to-right and top-to-bottom, to resize the image. This technique is often used to create variable-width buttons, which retain the same rounded corners but whose center region grows or shrinks as needed. For best performance, use a tiled area that is a 1x1 pixel area in size.
So you only need to use the amount of pixels you want to make unstretchable in the values of the UIEdgeInsetsMake
function.
Say you have an image of 21x50 points (21x50 pixels in standard definition, 42x100 pixels in Retina "@2x" definition) and want this image to be horizontally stretchable, keeping the 10 points on the left and on the right untouched when stretching the image, but only stretch the 1-point-wide band in the middle. Then you will use UIEdgeInsetsMake(0,10,0,10)
.
Don't bother that they are floats (that's useful for subpixelling resizing for example, but in practice you will probably only use integers (or floats with no decimal parts)
Be careful, this is an iOS5+ only method, not available prior iOS5. If you use pre-iOS5 SDK, use stretchableImageWithLeftCapWidth:topCapHeight:
instead.
[EDIT] Some tip I use since some time, as I never remember in which order the fields of the UIEdgeInsets
structure are — and in which order we are supposed to pass the arguments to UIEdgeInsetsMake
function — I prefer using the "designated inits" syntax like this:
UIEdgeInsets insets = { .left = 50, .right = 50, .top = 10, .bottom = 10 };
Or when an explicit cast is needed:
UIImage* rzImg = [image resizableImageWithCapInsets:(UIEdgeInsets){
.left = 50, .right = 50,
.top = 10, .bottom = 10
}];
I find it more readable, especially to be sure we don't mix the different borders/directions!