I'm trying to add images to my UISegmentedControl but the image is always automatically stretched to fill the entire control (see picture). I'm currently setting the image by calling setImage:forSegmentAtIndex:. How can set the image so that it maintains its aspect ratio? This seems like it should be an easy thing to do but I haven't been able to figure it out.
-
I have the opposite problem. I'm trying to get my image to stretch whereas it's just centered right now – Trespassers W Oct 21 '14 at 01:57
4 Answers
Use a @1x image that is small enough so that it does not need to be scaled at all, and the aspect ratio will not get messed up. Your @2x and @3x images can be larger, of course.

- 31
- 1
-
yup, works like a charm. If the image is small enough to fit in then it looks correct. If it is too large, it gets squeezed-in. – Leslie Godwin Jan 05 '19 at 06:56
When setting your image, use:
UIImage *myNewImage = [myOldImage resizableImageWithCapInsets:UIEdgeInsetsMake(top, left, bottom, right)];
[segment setImage:myNewImage forSegmentAtIndex:i];
Where top, left, bottom, and right
are the edges of the image you are willing to stretch. If you don't want any stretchable area, use UIEdgeInsetsZero
.

- 6,876
- 1
- 33
- 42
-
2I tried `UIEdgeInsetsZero` and now the image doesn't show up at all. – shoopdelang Jan 26 '14 at 22:14
You can use the following code to set a margin around your image when you are setting the image :
yourSegmentedControl.setImage(yourImage.resizableImage(withCapInsets: .init(top: 0, left: 10, bottom: 0, right: 10), resizingMode: .stretch), forSegmentAt: 0)
You can change the values of "top", "left", "bottom" and "right" as you want. This worked for me, I hope it will help!

- 406
- 3
- 12
Very similar to dalton's answer, though I build my view in interface builder, so had to replace the images, something like this:
self.codesDisplaySegment.contentMode = UIViewContentModeCenter;
for (int ii = 0 ; ii < self.codesDisplaySegment.numberOfSegments ; ++ii)
{
UIImage *img = [self.codesDisplaySegment imageForSegmentAtIndex: ii];
img = [img resizableImageWithCapInsets: UIEdgeInsetsZero];
[self.codesDisplaySegment setImage: img forSegmentAtIndex: ii];
}
Doing this solved my problem (which was as you describe.)

- 24,597
- 18
- 99
- 131