12

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.

UISegmentedControl with stretched icon

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
shoopdelang
  • 985
  • 2
  • 9
  • 20

4 Answers4

3

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.

wbd
  • 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
2

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.

dalton_c
  • 6,876
  • 1
  • 33
  • 42
0

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!

AW5
  • 406
  • 3
  • 12
-1

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

Olie
  • 24,597
  • 18
  • 99
  • 131