How to resize an Image of UIButton in Swift?


Sometime there may be need to resize the image displayed in UIButton for not availability of proper sized image because of some reason. Wrong size gives unwanted results like stretched out image pixels etc. In this post we are assuming simple UIButton with image only.

First solution:

We can update contentMode settings of imageView property of UIButton. Default value is .scaleToFill. It scales the image to fill the UIButton ignoring aspect ratio.

btn.imageView?.contentMode = .scaleAspectFit

This will solve the 50% of problem because UIButton will render the image maintaining the aspect ratio.

Now if in worst case scenario problem isn’t solved because of bigger dimension of image then we have second solution:

We can update the inset padding of UIButton along with .scaleAspectFit content mode.

btn.imageView?.contentMode = .scaleAspectFit
btn.imageEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)

Best solution:

Use well sized image suitable for UIButton. imageEdgeInsets is depreceated on iOS 15 onwards. UIButton.Configuration doesn’t give flexibility to resize the image natively.

You might also like: How To Scroll UICollectionView To End Of Footer or Header

You might also like: AVAudioPlayer not playing any sound

You might also like: How to Get Substring With NSRange in Swift 5

You might also like: iOS UIKit Animation Equivalent in Android's Kotlin Animation

More Articles

Recommended posts