Stretched images in UISegmentedControl

丶灬走出姿态 提交于 2019-12-10 12:37:05

问题


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.


回答1:


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.




回答2:


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.




回答3:


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:


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



来源:https://stackoverflow.com/questions/21369526/stretched-images-in-uisegmentedcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!