How to adjust an UIButton's imageSize?

前端 未结 16 2096
时光说笑
时光说笑 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:09

    Updated for Swift > 5

    set the size:

    button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
    

    set margins:

    button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    
    0 讨论(0)
  • 2021-01-29 22:12

    If I understand correctly what you're trying to do, you need to play with the buttons image edge inset. Something like:

    myLikesButton.imageEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
    
    0 讨论(0)
  • 2021-01-29 22:12

    Swift 3

    I set myButton width and height to 40 and my padding from EdgeInsetsMake is 15 all sides. I suggest to add a background color to your button to see the actual padding.

    myButton.backgroundColor = UIColor.gray // sample color to check padding
    myButton.imageView?.contentMode = .scaleAspectFit
    myButton.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15)
    
    0 讨论(0)
  • 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!
    }
    
    0 讨论(0)
  • 2021-01-29 22:17

    Heres the Swift version:

    myButton.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    
    0 讨论(0)
  • 2021-01-29 22:18

    you can use imageEdgeInsets property The inset or outset margins for the rectangle around the button’s image.

     [self.btn setImageEdgeInsets:UIEdgeInsetsMake(6, 6, 6, 6)];
    

    A positive value shrinks, or insets, that edge—moving. A negative value expands, or outsets, that edge.

    0 讨论(0)
提交回复
热议问题