swift - 如何以编程方式在 SWIFT 中设置 UIImage 的 alpha?

标签 swift uibutton uiimage uicontrolstate

我在这里找到了很多解决方案,但不是针对 Swift 的,而且我知道您可以使用 UIImageView 做到这一点,但在我的例子中,我需要一个以编程方式为 设置 alpha 透明背景图像界面按钮。最好是 UIImage 扩展!

let img = UIImage(named: "imageWithoutAlpha")
var imgInsets = UIEdgeInsetsMake(0, 24, 0, 24)
image = image!.resizableImageWithCapInsets(imgInsets)

let myButton = UIButton(frame: CGRect(x: 50, y: 50, width: img!.size.width, height: img!.size.height))
myButton.setBackgroundImage(img, forState: UIControlState.Normal)
myButton.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 20)
myButton.setTitle("Startbutton", forState: UIControlState.Normal)
myButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
myButton.sizeToFit()
view.addSubview(myButton)

当前结果:

current

期望的结果:

desired

最佳答案

幸运的是,我能够帮助自己,并想与您分享我的解决方案:

swift 3

// UIImage+Alpha.swift

extension UIImage {  

    func alpha(_ value:CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!   
    }
}

我将上述新的 Swift 扩展添加到我的项目中,然后我更改了 UIButton 示例,使其具有透明度为 50% 的 alpha 透明背景图像。

let img = UIImage(named: "imageWithoutAlpha")!.alpha(0.5)
let myButton = UIButton()

myButton.setBackgroundImage(img, for: .normal)

关于swift - 如何以编程方式在 SWIFT 中设置 UIImage 的 alpha?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28517866/

相关文章:

ios - 尝试从手机库中选择全景图像时 UIImagePickerController 崩溃

ios - 如何将字符串数据发送到 UIButton 标签?

ios - 将图像设置在背景中心,按钮周围有内部空间

iphone - 无法在 iPhone 中实现单选按钮

ios - 如何通过 TCP 将 IplImage 从服务器发送到 iPod 客户端 UIImage

ios - 在 iPhone 模拟器上成功安装证书后,在访问我的 Web 服务时仍然出现 SSL 错误

swift - 解码器是否需要具有 key 的外部数据表示?

ios - 无法在 Firebase 中保留 'posts' 的 'users' 引用

ios - 自定义 UIBarButton 项目图像

ios - bezierPathWithRoundedRect : gives bad result on retina screen