下面的代码在细节视图控制器中创建了一个带有渐变层的方形 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)
}
}
Run Code Online (Sandbox Code Playgroud)
您正在为您的方形视图提供cornerRadius,但没有将其添加到您的主视图中,而是创建了 backgroundLayer 并将其添加到您的主视图中。
BackgroundLayer 不是四舍五入,因为当您为方形视图的框架分配一个矩形(在您的情况下为正方形)时,会将一个矩形(在您的情况下为正方形)分配给 backgroundLayer,而没有任何cornerRadius。
您应该将 backgroundLayer 添加到方形视图中,然后将方形视图添加到主视图中。喜欢,
square.layer.insertSublayer(backgroundLayer, at: 1)
view.addSubview(square)
Run Code Online (Sandbox Code Playgroud)
也这样做,
square.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题。
| 归档时间: |
|
| 查看次数: |
2283 次 |
| 最近记录: |