gpt4 book ai didi

ios - 透明的 UIButton 标题

转载 作者:搜寻专家 更新时间:2023-11-01 05:45:43 24 4
gpt4 key购买 nike

如何从按钮背景中减去标题文本的形状?

enter image description here

我创建了一个自定义的 UIButton 类。目前添加边框和文本颜色的代码看起来很简单

layer.borderWidth = 2.0
layer.borderColor = buttonColor.CGColor
layer.cornerRadius = (CGFloat(bounds.height) + paddingVertical * 2.0) / 2.0
setTitleColor(buttonColor, forState: UIControlState.Normal)

关于如何从背景中减去按钮标题形状的任何建议。我需要将所有这些渲染为图像还是有更好的选择?

最佳答案

swift 4 的扩展

extension UIButton{
func clearColorForTitle() {

let buttonSize = bounds.size

if let font = titleLabel?.font{
let attribs = [NSAttributedStringKey.font: font]

if let textSize = titleLabel?.text?.size(withAttributes: attribs){
UIGraphicsBeginImageContextWithOptions(buttonSize, false, UIScreen.main.scale)

if let ctx = UIGraphicsGetCurrentContext(){
ctx.setFillColor(UIColor.white.cgColor)

let center = CGPoint(x: buttonSize.width / 2 - textSize.width / 2, y: buttonSize.height / 2 - textSize.height / 2)
let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: buttonSize.width, height: buttonSize.height))
ctx.addPath(path.cgPath)
ctx.fillPath()
ctx.setBlendMode(.destinationOut)

titleLabel?.text?.draw(at: center, withAttributes: [NSAttributedStringKey.font: font])

if let viewImage = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()

let maskLayer = CALayer()
maskLayer.contents = ((viewImage.cgImage) as AnyObject)
maskLayer.frame = bounds

layer.mask = maskLayer
}
}
}
}
}

用法:

button.clearColorForTitle()

关于ios - 透明的 UIButton 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27458101/

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