Swift - Setting CALayer bounds or frame not working

只愿长相守 提交于 2020-12-13 03:40:30

问题


I'm new to Swift, and I can't seem to figure out one of the most basic things - setting frame and bounds for a CALayer, so I can read them later.

I'm trying to see where a box is drawn on a CALayer to determine how close to the center of the layer it is.

I would have assumed the CALayer is the same size of the layer/view it's added to with subview, but when I look at the CALayer's frame or bounds it's zero. Same for the superview layer/view.

Any help would be much appreciated!

Goal: check where a box is written within a layer

Pseudo Code:

create new layer
draw a box on layer
look at box dimensions and compare to layer dimensions
if box near middle of the layer then print success

View/Layer Hierarchy (top to bottom)

 1. CALayer named shapeLayer
 2. CALayer named previewLayer (this is a AVCaptureVideoPreviewLayer)
 3. UIView named videoPreview

I can't set frame or bounds for any of the 3 views/layers. All i get is 0 back when I read the frame or bounds value.

Note, I've tried calling code in viewWillAppear as well, but same result.

override func viewDidLoad() {
    super.viewDidLoad()
    if let previewLayer = self.videoCapture.previewLayer {
        self.videoPreview.layer.addSublayer(previewLayer)
        videoCapture.previewLayer?.frame = videoPreview.bounds
    }

    if videoCapture.previewLayer?.frame != nil {

        videoCapture.previewLayer!.frame = CGRect(x:0, y:0, width:375, height: 667)

        let w = videoCapture.previewLayer!.frame.height
        let h = videoCapture.previewLayer!.frame.width

        NSLog("Print the height and width  w:%i, h:%i", w, h);

    }   
}

回答1:


You will get the frame of your layers when the view did layout its subviews:

override func viewDidLoad() {
    super.viewDidLoad()
    if let previewLayer = self.videoCapture.previewLayer {
        self.videoPreview.layer.addSublayer(previewLayer)
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    if let previewLayer = self.videoCapture.previewLayer {
        videoCapture.previewLayer?.frame = videoPreview.bounds
    }

    if videoCapture.previewLayer?.frame != nil {

        videoCapture.previewLayer!.frame = CGRect(x:0, y:0, width:375, height: 667)

        let w = videoCapture.previewLayer!.frame.height
        let h = videoCapture.previewLayer!.frame.width

        NSLog("Print the height and width  w:%i, h:%i", w, h)
    }
}


来源:https://stackoverflow.com/questions/48569864/swift-setting-calayer-bounds-or-frame-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!