如何将maskView成功地设置到UIView中?

4
我正在开发一个基于相机的应用程序,并希望在相机预览上制作一个模糊的叠层,在模糊视图中切出一个圆角矩形。
我一直尝试使用iOS 8引入的UIView的maskLayer来实现这个效果,但一直没有成功。
以下是我的代码:
// Blur the preview
UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIView *blurView = [[UIVisualEffectView alloc] initWithEffect:effect];
blurView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view insertSubview:blurView aboveSubview:imagePicker.view];

// Make blur view fill screen
{
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[blurView]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(blurView)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[blurView]-0-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(blurView)]];
}

// Add a rounded of transparency to the blurView  **not working**
UIView *mask = [[UIView alloc] initWithFrame:CGRectMake(50.f, 50.f, 50.f, 50.f)];
mask.alpha = 1.0f;
mask.backgroundColor = [UIColor redColor];
[blurView setMaskView:mask]; // Remove this line, and everything is frosted.  Keeping this line and nothing is frosted. 

从我的评论中可以看出,添加遮罩完全消除了毛玻璃效果(改变遮罩的不透明度没有任何作用)。我知道这不会产生我想要的效果(它应该只在矩形区域内呈现毛玻璃效果),但我无法让 maskView 在任何情况下正常工作。


2
代码的最后一行有错误。尝试修改为:[blurView setMaskView:mask]; - ninjaproger
@ninjaproger,我的帖子中有一个错误(现已更正)。不过还是谢谢你指出来。 - androidnotgenius
1个回答

6
UIView的API表示:
一个可选的视图,其 alpha 通道用于遮罩视图的内容。
最好的方式是使用UIImageView加载一个带有alpha通道的RGBA图像 - 从Photoshop导出带有透明度开关的PNG图像就可以了。然后将其调整大小,并将原点设置为0,0。
第二种方法是创建一个没有alpha值的UIView,即[UIColor clearColor],并添加一个具有alpha值的子视图[UIColor whiteColor];
UIView *mask = [[UIView alloc] initWithFrame:(CGRect){0,0,100,100}];
mask.backgroundColor = [UIColor clearColor];
UIView *areaToReveal = [[UIView alloc] initWithFrame:(CGRect){20,20,50,50}];
areaToReveal.backgroundColor = [UIColor whiteColor];
[mask addSubview:areaToReveal];
_myView.maskView = mask;

您可以使用 [UIColor colorFromRed: green: blue: alpha:x]; 添加更多的半透明 UIView ,其中 x 是 alpha 值。


如果您将[UIColor whiteColor]添加到代码中,那么它会更加正确,因为它基于新UIView的默认行为,当苹果决定更改它时,这可能会成为问题。无论如何,现在也是正确的。 - BootMaker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接