【问题标题】:How to scale image and center it on a UIButton in Swift?如何缩放图像并将其居中在 Swift 中的 UIButton 上?
【发布时间】:2014-12-26 05:42:10
【问题描述】:
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
var image = UIImage(named: "myimage.png") as UIImage!
button.frame = CGRectMake(0, 0, 100, 100)
button.setImage(image, forState: .Normal)

我在按钮上设置了一个图像,但我想将其缩放为小于按钮(例如图像应为 50,50)并位于按钮的中心。我如何在 Swift 中做到这一点?

【问题讨论】:

    标签: swift uibutton


    【解决方案1】:

    Xcode 8.3.1 • Swift 3.1

    let button = UIButton(type: .custom)
    let image = UIImage(named: "myimage.png")
    
    func buttonTouchDown(_ button: UIButton) {
        print("button Touch Down")
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100)
        button.backgroundColor = .clear
        button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown)
        button.setTitle("Title", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.setImage(image, for: .normal)
        button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25)
        view.addSubview(button)
    }
    

    【讨论】:

      【解决方案2】:

      有一种更简单的方法可以做到这一点,您不必处理内容插入。这里是:

      var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
      var image = UIImage(named: "myimage.png") as UIImage!
      button.frame = CGRectMake(0, 0, 100, 100)
      button.setImage(image, forState: .Normal)
      button.contentMode = .center
      button.imageView?.contentMode = .scaleAspectFit
      

      【讨论】:

        【解决方案3】:

        斯威夫特 5、斯威夫特 4、斯威夫特 3

        var image = UIImage(named: "myimage") as UIImage!   
        btnetc.setImage(image, for: .normal)
        btnetc.imageView?.contentMode = .scaleAspectFill
        

        btnetc.imageView?.contentMode = .scaleAspectFit
        

        btnetc.imageView?.contentMode = .scaleToFill
        

        【讨论】:

        • 如何将按钮图像的大小更改为 50x50?
        • 只需调整按钮大小,它会自动改变高度和宽度
        • 按钮应该是 100x100,图片是 50x50,我不明白你的解决方案是如何处理这个问题的?
        • 您只需获取按钮内部图像视图并重新绘制大小您想要的任何问题都会得到解决
        【解决方案4】:

        或在选择您的UIButton 后通过XIB

        只要确保你的插图都是一样的。


        【讨论】:

          【解决方案5】:

          Xcode 13,斯威夫特 5

          使用情节提要,选择按钮,然后在尺寸检查中单击内容插图上方的尺寸下拉菜单。有一个尺寸列表可供选择,这将调整您的图像尺寸(如果您使用系统图像)。当您将故事板上的按钮添加到视图控制器时,默认大小已设置。

          【讨论】:

            猜你喜欢
            • 2018-09-08
            • 2011-01-02
            • 1970-01-01
            • 1970-01-01
            • 2011-01-02
            • 1970-01-01
            • 1970-01-01
            • 2012-03-09
            • 1970-01-01
            相关资源
            最近更新 更多