iOS - 将CAGradientLayer集中到父UIView中

时间:2017-06-29 19:25:04

标签: ios swift xcode uiview calayer

我的bgLayer: CAGradientLayer 尺寸更大,然后是父视图bgView。正在使用bgView.layer.insertSublayer正确插入图层,但我无法使用较小的bgLayer创建bgView的框架。

我如何将bgLayer集中到我的bgView

1 个答案:

答案 0 :(得分:1)

我相信这就是你的意思......

较大的渐变视图以较小的UIView为中心。第一张图片位于.clipsToBounds = true,第二张图片位于.false.

enter image description here enter image description here

两张图片都使用相同的视图尺寸:100 x 100和相同的渐变尺寸:150 x 150。您可以将此代码粘贴到Playground页面以查看其工作原理。

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)