How to adjust an UIButton's imageSize?

前端 未结 16 2095
时光说笑
时光说笑 2021-01-29 21:40

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         


        
16条回答
  •  一生所求
    2021-01-29 22:14

    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!
    }
    

提交回复
热议问题