2017-06-29 1 views
0

J'ai un bgLayer: CAGradientLayeravec des dimensions plus grandes puis c'est la vue parente bgView. La couche est insérée correctement en utilisant bgView.layer.insertSublayer, mais je ne peux pas créer le cadre de mon bgLayer centralisé avec mon plus petit bgView. Comment puis-je centraliser mon bgLayer dans mon bgView?iOS - centraliser CAGradientLayer dans le parent UIView

Répondre

1

Je crois que c'est ce que vous voulez dire ...

Agrandir Gradient centrée sur UIView plus petit. Première image est avec .clipsToBounds = true, deuxième image .false.:

enter image description hereenter image description here

Les deux images utilisent la même taille d'affichage: 100 x 100 et la même taille de gradient: 150 x 150. Vous pouvez coller ce code dans une page Playground pour voir comment cela fonctionne.

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) 
+0

Génial! J'étais confus au sujet de la formule pour les centrer tous les deux. – juniorgarcia