我在弄清楚如何使 UIButton
标题透明以使其颜色与 super View 的渐变背景颜色相同时遇到了一些麻烦。
我看过一个关于将按钮渲染为图像的帖子,但它是在带有旧 CG API 的 objective-c 中,我想知道是否有人可以就解决此问题的更好方法提供建议。
如有任何建议,我们将不胜感激!
这是我目前所拥有的:
import UIKit
import Foundation
class MainViewController: UIViewController {
let headingLabel: UILabel = {
let label = UILabel()
label.text = "Hello, World"
label.font = label.font.withSize(30)
label.textColor = .white
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let continueButton: UIButton = {
let button = UIButton()
button.setTitleColor(.black, for: .normal)
button.setTitle("Continue", for: .normal)
button.layer.cornerRadius = 10
button.backgroundColor = .white
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
let gradientLayer: CAGradientLayer = {
let layer = CAGradientLayer()
layer.colors = [
UIColor(red: 96/255, green: 165/255, blue: 238/255, alpha: 1.0).cgColor,
UIColor(red: 233/255, green: 97/255, blue: 99/255, alpha: 1.0).cgColor,
]
layer.startPoint = CGPoint(x: 0.0, y: 0.0)
layer.endPoint = CGPoint(x: 1.0, y: 1.0)
return layer
}()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = true
}
func setupView() {
// root view
gradientLayer.frame = view.frame
view.layer.addSublayer(gradientLayer)
view.addSubview(headingLabel)
view.addSubview(continueButton)
// constraints
let views: [String: UIView] = [
"headingLabel": headingLabel,
"continueButton": continueButton,
"superview": view
]
var constraints: [NSLayoutConstraint] = []
let verticalHeadingLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat:
"V:|-100-[headingLabel(30)]",
options: [],
metrics: nil,
views: views)
constraints += verticalHeadingLabelConstraint
let horizontalHeadingLabelConstraint = NSLayoutConstraint.constraints(withVisualFormat:
"H:|-[headingLabel]-|",
options: .alignAllCenterX,
metrics: nil,
views: views)
constraints += horizontalHeadingLabelConstraint
let verticalContinueButtonConstraint = NSLayoutConstraint.constraints(withVisualFormat:
"V:[continueButton(50)]-100-|",
options: [],
metrics: nil,
views: views)
constraints += verticalContinueButtonConstraint
let horizontalContinueButtonConstraint = NSLayoutConstraint.constraints(withVisualFormat:
"H:|-100-[continueButton]-100-|",
options: [],
metrics: nil,
views: views)
constraints += horizontalContinueButtonConstraint
view.addConstraints(constraints)
}
}
最佳答案
如果你想这样做,你最好考虑一个面具。
为此,您必须将文本写入位图上下文并将其用作纯色上的 mask 。
如果找到可以帮助您的东西 here .
只需几个步骤:
- 您创建图像上下文
- 您将白色文本设置为用作 mask
- 在上下文中绘制文本
- 你创建面具
- 您根据纯色创建另一个图像
- 你剪辑它们
关于ios - 在 Swift 4 中使用掩码使 UIButton 文本透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137112/