The result is not what you expected because the original .png image you are using higher in resolution. You should never use a "big" image to display only a small picto. The full image will be loaded in memory, and only 10% of its pixels will be displayed, so you will use a lot of memory for nothing.
What you can do if you really want to use this resource is to create a new image with code before, and use this new generated image.
The following method returns a new image you can use in your UISegmentedControl
, and you can release the big one.
func image(with image: UIImage?, scaledTo newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(newSize)
image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
In your code:
let testTypeSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["One", "Two"])
sc.selectedSegmentIndex = 0
sc.translatesAutoresizingMaskIntoConstraints = false
return sc
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(testTypeSegmentedControl)
let newImage = image(with: (UIImage(named: "watermelon.png")), scaledTo: CGSize(width: 32, height: 30))
testTypeSegmentedControl.setImage(newImage , forSegmentAt: 0)
}