Stretched images in UISegmentedControl

2019-06-15 08:06发布

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

4条回答
神经病院院长
2楼-- · 2019-06-15 08:29

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.

查看更多
Evening l夕情丶
3楼-- · 2019-06-15 08:39

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!

查看更多
一夜七次
4楼-- · 2019-06-15 08:41

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

查看更多
该账号已被封号
5楼-- · 2019-06-15 08:50

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.

查看更多
登录 后发表回答