我正在尝试将矩形视图添加到我的相机预览图层。我试过UIView和CALayer两种方式。在这两种情况下,帧值都相同,但它们最终都处于不同的位置。
一个黑色边框是CALayer(featureLayer),浅色背景是UIView(_cardHolder)。
在viewWillAppear中:
CALayer *featureLayer = [[CALayer alloc]init];
featureLayer.borderWidth=3;
featureLayer.backgroundColor=[[UIColor orangeColor]CGColor];
featureLayer.opacity = 0.5;
featureLayer.position = CGPointMake(0, 0);
[featureLayer setFrame:self.cardHolder.frame];
[self.videoPreviewLayer addSublayer:featureLayer];
(lldb) po featureLayer <CALayer:0x1c4423b20; position = CGPoint (160 283.5); bounds = CGRect (0 0; 288 181); allowsGroupOpacity = YES; opacity =
0.5; backgroundColor = <CGColor 0x1c40b1d00> [<CGColorSpace 0x1c00bb120> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 1 0.5 0 1 ); borderWidth = 3>
(lldb) po featureLayer.frame
(origin = (x = 16, y = 193), size = (width = 288, height = 181))
(lldb) po self.cardHolder <UIView: 0x123dcbc50; frame = (16 193; 288 181); autoresize = RM+BM; layer = <CALayer: 0x1c043eb40>>
(lldb) po self.videoPreviewLayer <AVCaptureVideoPreviewLayer:0x1c0623ae0; position = CGPoint (187.5
333.5); bounds = CGRect (0 0; 375 667); sublayers = (<CALayer: 0x1c0623800>, <CALayer: 0x1c4423b20>); masksToBounds = YES; allowsGroupOpacity = YES; inheritsTiming = NO; >
我错过了什么吗?
将代码放在viewDidAppear
/ viewDidLayoutSubviews
以外的方法中的问题是真实的帧还没有渲染,所以它应该是这样的,但要记住将它包装在一次bool中,因为这个方法被多次调用
-(void)viewDidLayoutSubviews
if(once)
{
once = No;
CALayer *featureLayer = [[CALayer alloc]init];
featureLayer.borderWidth=3;
featureLayer.backgroundColor=[[UIColor orangeColor]CGColor];
featureLayer.opacity = 0.5;
featureLayer.position = CGPointMake(0, 0);
[featureLayer setFrame:self.cardHolder.frame];
[self.videoPreviewLayer addSublayer:featureLayer]
}
}