以下代码在详细视图控制器内创建一个带有渐变图层的方形UIView框架。但是,square.layer.cornerRadius不显示。它仍然是正方形。
class Colors {
let colorTop = UIColor(red: 68.0/255.0, green: 107.0/255.0, blue: 207.0/255, alpha: 1.0).cgColor
let colorBottom = UIColor(red: 68.0/255.0, green: 108.0/255.0, blue: 179.0/255, alpha: 1.0).cgColor
let gl: CAGradientLayer
init() {
gl = CAGradientLayer()
gl.colors = [ colorTop, colorBottom]
gl.locations = [ 0.0, 1.0]
}
}
class DetailViewController: UIViewController {
func viewWillAppear {
let colors = Colors() // is a class that creates the gradient
let square = UIView(frame: CGRect(x: 18, y: 109, width: 60, height: 60))
square.layer.cornerRadius = 10
let backgroundLayer = colors.gl
backgroundLayer.frame = square.frame
backgroundLayer.maskToBounds = true
view.layer.insertSublayer(backgroundLayer, at: 1)
}
}
答案 0 :(得分:3)
我在原始GradientView中添加了一些其他属性,以便为其添加所需的功能:
@IBDesignable
class GradientView: UIView {
@IBInspectable var startColor: UIColor = .black
@IBInspectable var endColor: UIColor = .white
@IBInspectable var startLocation: Double = 0.05
@IBInspectable var endLocation: Double = 0.95
@IBInspectable var horizontalMode: Bool = false
@IBInspectable var diagonalMode: Bool = false
// add border color, width and corner radius properties to your GradientView
@IBInspectable var cornerRadius: CGFloat = 0
@IBInspectable var borderColor: UIColor = .clear
@IBInspectable var borderWidth: CGFloat = 0
override class var layerClass: AnyClass { return CAGradientLayer.self }
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
override func layoutSubviews() {
super.layoutSubviews()
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
}
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
// add border and corner radius also to your layer
gradientLayer.cornerRadius = cornerRadius
gradientLayer.borderColor = borderColor.cgColor
gradientLayer.borderWidth = borderWidth
}
}
答案 1 :(得分:1)
您将cornerRadius提供给方形视图,但不将其添加到主视图中,而是创建backgroundLayer并将其添加到主视图中。
BackgroundLayer没有舍入为您指定方形视图的框架时矩形(在您的情况下为方形)被分配给backgroundLayer而没有任何cornerRadius。
您应该将backgroundLayer添加到方形视图中,然后将方形视图添加到主视图中。像,
.connect()
也这样做,
square.layer.insertSublayer(backgroundLayer, at: 1)
view.addSubview(square)
这可以解决您的问题。
答案 2 :(得分:0)
我知道你是通过编程方式完成的,但是这里有另一个提示,如果它是一个故事板,那么你只需启用它即可启用" Clip to Bounds"在UIView上。当我添加渐变并以编程方式设置cornerRadius时,这总是适用于我。
答案 3 :(得分:0)
将渐变的角半径设置为等于视图的角半径。 (您要在其上应用渐变的视图)
free()