private let containerView: UIView = {
let view = UIView()
var gradientBorderLayer: CAGradientLayer?
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.cornerRadius = 15
view.layer.borderWidth = 1
gradientBorderLayer = view.getGradientWithBorderLayer(with: .gradientColorFirst, .gradientColorSecond)
view.layer.addSublayer(gradientBorderLayer ?? CAGradientLayer())
return view
}()
func getGradientWithBorderLayer(with firstColor: UIColor, _ secondColor: UIColor) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
let shapeLayer = CAShapeLayer()
gradientLayer.frame = CGRect(origin: CGPoint.zero, size: bounds.size)
gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.1)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.1)
shapeLayer.lineWidth = 3
shapeLayer.path = UIBezierPath(roundedRect: bounds.insetBy(dx: shapeLayer.lineWidth, dy: shapeLayer.lineWidth), cornerRadius: layer.cornerRadius).cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
gradientLayer.mask = shapeLayer
return gradientLayer
}
我正在尝试像这样制作视图边框颜色。但是视图的边框颜色不是渐变颜色,而是黑色。这可能是什么原因?
你的代码缺少很多上下文,所以我所做的是将所有功能封装到一个子类中
UIView
这样你就可以更好地理解渐变层的工作原理。由于缺少上下文,很难查明您遇到的问题。我不知道变量是否只是超出了范围,它们在被读取时是否对函数不可用,或者其他原因。我实际上并没有从你的代码中改变任何重要的东西,这意味着你已经掌握了这个概念。您的问题似乎只是实施。
您可以将其复制并粘贴到 Xcode Playground(通过转到 Editor > Live View 启用实时视图)以查看它的实际效果。
import PlaygroundSupport
import UIKit
class CustomView: UIView {
init() {
super.init(frame: .zero)
clipsToBounds = true
}
required init?(coder: NSCoder) {
return nil
}
override func draw(_ rect: CGRect) {
let h = rect.height
let w = rect.width
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: .zero, size: CGSize(width: w, height: h))
gradientLayer.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 10
shapeLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: 20).cgPath
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
gradientLayer.mask = shapeLayer
layer.cornerRadius = 20
layer.addSublayer(gradientLayer)
}
}
class Preview: UIViewController {
override func loadView() {
view = UIView()
view.backgroundColor = .gray
let x = CustomView()
x.backgroundColor = UIColor.white
x.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(x)
x.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
x.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
x.widthAnchor.constraint(equalToConstant: 96).isActive = true
x.heightAnchor.constraint(equalToConstant: 96).isActive = true
}
}
PlaygroundPage.current.liveView = Preview()