Swift - 以编程方式在大屏幕上显示UIButton图像

时间:2015-08-18 17:01:21

标签: ios swift layout uibutton

我正在尝试使用swift

以编程方式设置我的按钮样式
let acButton = UIButton.buttonWithType(.Custom) as! UIButton
acButton.frame = CGRectMake(0, 0, buttonWidth, buttonHeight)
acButton.setImage(UIImage(named: "ac"), forState: .Normal)
acButton.imageEdgeInsets = UIEdgeInsetsMake(10,10,10,10)
acButton.layer.borderWidth = 1
acButton.layer.borderColor = UIColor.grayColor().CGColor
acButton.addTarget(self, action: "acPressed", forControlEvents: .TouchUpInside)
self.view.addSubview(acButton)

但我在像iPad Air这样的大屏幕设备上遇到的问题(见图)图像不适合按钮框架,我也尝试将图像设置为按钮的backgroundImage,但我没有得到什么我想要原因 imageEdgeInsets 似乎没有在backgroundImage上工作。

解决方案:

使用imageWithCGImage:scale:orientation获取图片,如以下方法:

func getScaledImage(img: UIImage, btn: UIButton) -> UIImage {

        // Check which dimension (width or height) to pay respect to and
        // calculate the scale factor
        var imgRatio: CGFloat = img.size.width / img.size.height
        var btnRatio = btn.frame.size.width / btn.frame.size.height
        var scaleFactor = (imgRatio > btnRatio) ? img.size.width / btn.frame.size.width : img.size.height / btn.frame.size.height

        // Create image using scale factor
        var scaledImg = UIImage(CGImage: img.CGImage, scale: scaleFactor, orientation: UIImageOrientation.Up)
        return scaledImg!

    }

为了实现这一点,我们写道:

let acImage = getScaledImage(UIImage(named: "ac")!, btn: acButton)
acButton.setImage(acImage, forState: .Normal)

所以最终代码

let acButton = UIButton.buttonWithType(.Custom) as! UIButton
acButton.frame = CGRectMake(0, 0, buttonWidth, buttonHeight)

let acImage = getScaledImage(UIImage(named: "ac")!, btn: acButton)
acButton.setImage(acImage, forState: .Normal)

acButton.imageEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20)
acButton.addTarget(self, action: "acPressed", forControlEvents: .TouchUpInside)
basicCalculatorView.addSubview(acButton)

3 个答案:

答案 0 :(得分:1)

你尝试过添加约束吗?这应该可以扩展它。

答案 1 :(得分:0)

您可能需要设置UIButton contentMode

    acButton.contentMode = UIViewContentMode.ScaleAspectFit

答案 2 :(得分:0)

尝试设置backgroundImage,而不是仅设置图像。

acButton.setBackgroundImage(UIImage(named: "image.jpg"), forState: .Normal)

检查它是否有效