Swift-设置CALayer边界或框架不起作用 [英] Swift - Setting CALayer bounds or frame not working
问题描述
我是Swift的新手,我似乎无法弄清最基本的事情之一-为CALayer设置框架和界限,所以我以后可以阅读它们.
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.
我试图查看在CALayer上绘制一个框的位置,以确定它与图层中心的距离有多近.
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.
我应该假定CALayer的大小与添加到子视图中的图层/视图的大小相同,但是当我查看CALayer的帧或边界时,它的大小为零.超级视图层/视图也是如此.
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.
任何帮助将不胜感激!
目标:检查框在图层中的写入位置
Goal: check where a box is written within a layer
伪代码:
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
我无法为3个视图/图层中的任何一个设置框架或边界.当我读取frame或bounds值时,我得到的只是0.
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.
注意,我也尝试过在viewWillAppear中调用代码,但结果相同.
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);
}
}
推荐答案
当视图对子视图进行布局时,您将获得图层的框架:
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)
}
}
这篇关于Swift-设置CALayer边界或框架不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!