我有一个带有SDWebImage
下载背景图片的按钮。我想保持高度不变并通过保持纵横比而不是切割图像来改变宽度。只是恒定的高度和动态宽度。这有什么不对?
//CODE FROM FUNCTION ---
button.sd_setBackgroundImage(with: url, for: .normal, placeholderImage: UIImage(named: "img"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
let view = UIView(frame: CGRect(x: 0, y: 0, width: self.resizeImage(image: image!, newHeight: 100), height: 100))
button.frame = view.frame
})
view.addSubview(button)
return view
这是我的助手功能
func resizeImage(image: UIImage, newHeight: CGFloat) -> CGFloat {
let scale = newHeight / image.size.height
let newWidth = image.size.width * scale
return newWidth
}
答案 0 :(得分:0)
您可以为按钮宽度创建 IBoutlet NSLayoutConstraint ,并根据图像宽度在运行时为按钮宽度提供常量值(下载图像后)。