How can I adjust the image size of the UIButton? I am setting the image like this:
[myLikesButton setImage:[UIImage imageNamed:@\"icon-heart.png\"] forState:UICo
One approach is to resize the UIImage in code like the following. Note: this code only scales by height, but you can easily adjust the function to scale by width as well.
let targetHeight = CGFloat(28)
let newImage = resizeImage(image: UIImage(named: "Image.png")!, targetHeight: targetHeight)
button.setImage(newImage, for: .normal)
fileprivate func resizeImage(image: UIImage, targetHeight: CGFloat) -> UIImage {
// Get current image size
let size = image.size
// Compute scaled, new size
let heightRatio = targetHeight / size.height
let newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
// Create new image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// Return new image
return newImage!
}