我想在UIView上创建渐变边框。
以下代码可以为Box1视图生成实体。
我发现的所有内容都不允许我将frameColor更改为渐变。
var frameColor = UIColor.red.cgColor
var leftBorder = CALayer()
leftBorder.frame = CGRect(x: 0.0, y: 0, width: 1, height: box1.frame.size.height )
leftBorder.backgroundColor = frameColor
我正在使用Swift 5和Xcode 11。
谢谢。
答案 0 :(得分:2)
尝试以下扩展名
public extension UIView {
private static let kLayerNameGradientBorder = "GradientBorderLayer"
func setGradientBorder(
width: CGFloat,
colors: [UIColor],
startPoint: CGPoint = CGPoint(x: 0.5, y: 0),
endPoint: CGPoint = CGPoint(x: 0.5, y: 1)
) {
let existedBorder = gradientBorderLayer()
let border = existedBorder ?? CAGradientLayer()
border.frame = bounds
border.colors = colors.map { return $0.cgColor }
border.startPoint = startPoint
border.endPoint = endPoint
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0).cgPath
mask.fillColor = UIColor.clear.cgColor
mask.strokeColor = UIColor.white.cgColor
mask.lineWidth = width
border.mask = mask
let exists = existedBorder != nil
if !exists {
layer.addSublayer(border)
}
}
func removeGradientBorder() {
self.gradientBorderLayer()?.removeFromSuperlayer()
}
private func gradientBorderLayer() -> CAGradientLayer? {
let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
if borderLayers?.count ?? 0 > 1 {
fatalError()
}
return borderLayers?.first as? CAGradientLayer
}
}
用法
self.borderView.setGradientBorder(width: 5.0, colors: [UIColor.red , UIColor.blue])
我希望这能满足您的要求。
答案 1 :(得分:0)
目前尚无现成的方法,但是您可以自己构建。
在我的头顶上,这种方法可能看起来像这样:
创建一个CAGradientLayer
并将其设置为绘制渐变为
创建一个CAShapeLayer
,其中包含一个空矩形,
框架。
添加形状图层作为渐变图层的蒙版。
将渐变层添加为视图的子层 内容层。