Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

ios - How does UIEdgeInsetsMake work?

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:

  • Top
  • Left
  • Bottom
  • Right

But they're floats so I don't know how to set that to an image, thanks! :D

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...