【发布时间】:2016-06-16 08:41:23
【问题描述】:
我正在尝试向屏幕添加一个按钮并以编程方式对其进行编辑,但大多数编辑都没有响应。
这是按钮代码:
@IBOutlet weak var buttonTest: UIButton!
let screen = UIScreen.mainScreen().bounds
let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50))
buttonTest.frame = CGRect(x: 0, y: screen.height - 300, width: screen.width * 0.5, height: screen.width * 0.5)
buttonTest.setImage(buttonImg, forState: .Normal)
buttonTest.setTitle("Test", forState: .Normal)
buttonTest.imageView?.contentMode = .ScaleAspectFit
view.addSubview(buttonTest)
ResizeImage 功能有效,我已经在其他视图控制器中使用过它。下面引用了此代码。 buttonTest.frame 方法不起作用,按钮将始终保持在同一个位置而无需编辑大小。图像也没有加载,在图像应该在的地方,我只能看到一个蓝色方块。
有谁知道如何解决这个问题?提前致谢!
ResizeImage 函数:
func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
【问题讨论】:
-
试试 buttonTest.imageView?.imageRenderingMode = .AlwaysOriginal
-
这并没有直接工作,但我是这样使用的:
let buttonImg = ResizeImage(UIImage(named: "Blokker")!, targetSize: CGSize(width: 50, height: 50)).imageWithRenderingMode(.AlwaysOriginal) -
对框架问题有任何想法吗?
标签: ios swift uibutton uiimage