如何以编程方式在 SWIFT 中设置 UIImage 的 alpha? [英] How to set the alpha of an UIImage in SWIFT programmatically?

查看:24
本文介绍了如何以编程方式在 SWIFT 中设置 UIImage 的 alpha?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found a lot solutions here but not for Swift, and I know you can do this with a UIImageView, but in my case i need an programmatically set alpha transparent background image for an UIButton. Best would be an UIImage extension!

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)

当前结果:

想要的结果:

推荐答案

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

Luckily I was able to help myself and would like to share with you my solution:

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 透明背景图像.

The above new Swift extension I added to my project and then I changed the UIButton example as follows, to have an alpha transparent background image with a transparency of 50%.

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

myButton.setBackgroundImage(img, for: .normal)

这篇关于如何以编程方式在 SWIFT 中设置 UIImage 的 alpha?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆