我正在尝试使用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)
答案 0 :(得分:1)
答案 1 :(得分:0)
您可能需要设置UIButton
的 contentMode :
acButton.contentMode = UIViewContentMode.ScaleAspectFit
答案 2 :(得分:0)
尝试设置backgroundImage,而不是仅设置图像。
acButton.setBackgroundImage(UIImage(named: "image.jpg"), forState: .Normal)
检查它是否有效