【发布时间】:2014-09-30 13:33:24
【问题描述】:
我以前做过简单的 CALayer 蒙版,但我想我对它们的作用感到困惑。我正在尝试使用几 (2) 个视图来产生打孔效果。
这是我目前所拥有的。我正在寻找一个带有打孔标签和图像的白色正方形(这样您就可以通过它看到棕色背景。我哪里出错了?
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
self.viewToPunch = [[UIView alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.viewToPunch];
self.viewToPunch.backgroundColor = [UIColor whiteColor];
self.punchLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.punchLabel.textColor = [UIColor blackColor];
self.punchLabel.font = [UIFont boldSystemFontOfSize:20.0];
self.punchLabel.text = @"punch";
self.punchLabel.textAlignment = NSTextAlignmentCenter;
self.punchImage = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"plus"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
[self.punchImage setContentMode:UIViewContentModeCenter];
self.viewsToPunch = @[self.punchLabel,self.punchImage];
[self punch:self.viewToPunch withUIViews:self.viewsToPunch];
}
- (void)punch:(UIView *) viewToPunch withUIViews:(NSArray *)viewsToPunch
{
CALayer *punchMask = [CALayer layer];
punchMask.frame = viewToPunch.frame;
NSMutableArray *sublayers = [[NSMutableArray alloc] init];
for (UIView *views in viewsToPunch){
[sublayers addObject:views.layer];
}
punchMask.sublayers = sublayers;
punchMask.masksToBounds = YES;
viewToPunch.layer.mask = punchMask;
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
self.viewToPunch.frame = CGRectMake(50, 50, 100, 100);
self.punchLabel.frame = CGRectMake(0, 0, 100, 100);
self.punchImage.frame = CGRectMake(0, 0, self.viewToPunch.frame.size.width, 40.);
[self punch:self.viewToPunch withUIViews:self.viewsToPunch];
}
因此,不仅框架似乎已关闭,而且似乎与打孔相反。如何反转蒙版并修复框架?
非常感谢您的帮助!我把它放在了一个方法 push:withUIViews: 中,所以我希望可以在其他领域重用它。
【问题讨论】:
-
你能在问题中写下你认为面具的作用和作用。另外,为什么要将框架设置为零矩形?
-
这就是我编码的方式 - 所有帧都是 cgrectzero,我在 viewWillLAyoutSubviews 或 layoutSubviews 中调整大小(因此动画、帧更改等会自动处理。我认为 CALayer 蒙版的工作方式是像素它按像素检查遮罩上的 Alpha 通道,并通过遮罩上的 Alpha 值调整另一个视图上的 Alpha。