gpt4 book ai didi

ios - 按钮中的图像无法加载,我只得到一个蓝色方 block

转载 作者:行者123 更新时间:2023-11-30 13:20:05 25 4
gpt4 key购买 nike

我正在尝试向屏幕添加一个按钮并以编程方式对其进行编辑,但大多数编辑都没有响应。

这是按钮代码:

@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 函数有效,我已经在其他 View Controller 中使用了它。下面引用了该代码。 ButtonTest.frame 方法不起作用,按钮将始终保持在同一位置,而无需编辑大小。图像也无法加载,在图像应该所在的位置,我只能看到一个蓝色方 block 。

有谁知道这个问题怎么解决吗?提前致谢!

调整图像大小函数:

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
}

最佳答案

我已经在评论中回答了您问题的第一部分

如果您希望图像与源相同,请使用imageView.imageRenderingMode = .AlwaysOriginal

imageView.imageRenderingMode = .AlwaysTemplate 如果您希望图像与其容器具有相同的颜色(没有 Alpha channel 的图像将是彩色方 block )

对于框架问题,为什么是下面这行?删除它。

view.addSubview(buttonTest) 

Buttontest 已经有一个 super View ,因为它是来自 Storyboard/xib 的导出。另外,如果您使用 Storyboard /xib 设计按钮,请不要更改框架矩形。您应该学习如何为此使用约束。

关于ios - 按钮中的图像无法加载,我只得到一个蓝色方 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com