我有一个尺寸更大的bgLayer: CAGradientLayer
然后它是父视图bgView
。使用bgView.layer.insertSublayer
正确插入层,但无法使用较小的bgLayer
集中创建bgView
的帧。
如何将bgLayer
集中到bgView
中?
最佳答案
我相信这就是你的意思。。。
以较小的UIView为中心的较大渐变视图。第一个图像带有.clipsToBounds = true
,第二个图像带有.false.
:
两个图像使用相同的视图大小:100 x 100
和相同的渐变大小:150 x 150
。您可以将此代码粘贴到游乐场页面中,以查看其工作原理。
import UIKit
import PlaygroundSupport
let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
container.backgroundColor = UIColor(red: 0.3, green: 0.5, blue: 1.0, alpha: 1.0)
PlaygroundPage.current.liveView = container
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 150 x 150 frame for the gradient layer
let gFrame = CGRect(x: 0, y: 0, width: 150, height: 150)
// 100 x 100 frame for the View
let vFrame = CGRect(x: 100, y: 100, width: 100, height: 100)
let v = UIView(frame: vFrame)
self.view.addSubview(v)
// add a border to the UIView so we can see its frame
v.layer.borderWidth = 2.0
// set up the Gradient Layer
let gradient = CAGradientLayer()
gradient.colors = [UIColor.red.cgColor,UIColor.yellow.cgColor]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
// set the initial size of the gradient frame
gradient.frame = gFrame
// center the gradient frame over (or inside, if smaller) the view frame
gradient.frame.origin.x = (v.frame.size.width - gradient.frame.size.width) / 2
gradient.frame.origin.y = (v.frame.size.height - gradient.frame.size.height) / 2
// add the gradient layer to the view
v.layer.insertSublayer(gradient, at: 0)
// set to true to clip the gradient layer
// set to false to allow the gradient layer to extend beyond the view
v.clipsToBounds = true
}
}
let vc = ViewController()
container.addSubview(vc.view)
关于ios - iOS-将CAGradientLayer集中到父UIView中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44833425/