'Change the size of UIButton’s imageView
I am working on a subclass of UIButton, let’s call it MyButton. In most cases, buttons of this subclass will have both image and title.
I am having troubles configuring MyButton’s imageView size. The goal is to limit the size of the image, so that larger images are resized and fit into a 32-by-32 square.
For testing purposes, I added a 128-by-128-pixel image, and set imageView’s backgroundColor to green.
Below is what the button looked like when I added the image. Both the imageView and its image had the size of 128 by 128 pixels.

After I overrode MyButton’s intrinsicContentSize with CGSize(width: 160, height: 50) and set the button’s imageView’s contentMode to .scaleAspectFit, the imageView resized, but only in height—it’s still 128 pixels wide, which causes the button’s title to truncate.

I’ve seen a lot of articles on how to resize the image inside the imageView using imageEdgeInsets. This is not what I am looking for since in all those articles the imageView preserves its size and only adds padding around the image.
Changing the imageView’s frame or bounds produces no result.
Any thoughts on how I can resize the button’s imageView?
Solution 1:[1]
let customButtonImage = MyButton.currentImage
now you have your button image resize it using @jay's extension for resizing image
let newimage = customButtonImage. resizedImage(size:requiredSize)
Reset image to button
self.setImage(newimage, for: .normal) //normal or what state your want
@jays extension
extension UIImage
{
func resizedImage(Size sizeImage: CGSize) -> UIImage?
{
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: sizeImage.width, height: sizeImage.height))
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
self.draw(in: frame)
let resizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.withRenderingMode(.alwaysOriginal)
return resizedImage
}
}
Solution 2:[2]
You can resize the image and then ad to button's image. Below you can find resize image code.
extension UIImage
{
func resizedImage(Size sizeImage: CGSize) -> UIImage?
{
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: sizeImage.width, height: sizeImage.height))
UIGraphicsBeginImageContextWithOptions(frame.size, false, 0)
self.draw(in: frame)
let resizedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.withRenderingMode(.alwaysOriginal)
return resizedImage
}
}
Button ui extension.
@IBInspectable var sizeImage: CGSize {
get {
return self.imageView?.image?.size ?? CGSize.zero
}
set {
if let image = self.imageView?.image {
let imgUpdate = image.resizedImage(Size: newValue)
self.setImage(imgUpdate, for: .normal)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
