目标c有一些答案,但没有找到任何关于swift的答案。
我想在中间创建一个带有透明圆圈的暗视图,以便用户可以看到子视图并与之交互。如何使用swift实现它。
更准确地说,我正在寻找像whatsapp个人资料图片实现的结果。中间有这个透明圆圈,用户可以看到图片并滚动例如。
感谢您的帮助!
答案 0 :(得分:4)
Cyril的回答被翻译为 swift 以防止额外输入:
func circularOverlayMask() -> UIImage {
let bounds = self.view.bounds
let width = bounds.size.width
let height = bounds.size.height
let diameter = width
let radius = diameter / 2
let center = CGPointMake(width / 2, height / 2)
// Create the image context
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
// Create the bezier paths
let clipPath = UIBezierPath(rect: bounds)
let maskPath = UIBezierPath(ovalInRect: CGRectMake(center.x - radius, center.y - radius, diameter, diameter))
clipPath.appendPath(maskPath)
clipPath.usesEvenOddFillRule = true
clipPath.addClip()
UIColor(white: 0, alpha: 0.5).setFill()
clipPath.fill()
let finalImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
return finalImage
}
答案 1 :(得分:2)
这是我在项目中用来创建圆形蒙版的方法(这不是在Swift中,但可以轻松翻译):
- (UIImage *)circularOverlayMask
{
// Constants
CGRect bounds = self.navigationController.view.bounds;
CGFloat width = bounds.size.width;
CGFloat height = bounds.size.height;
CGFloat diameter = width - (INNER_EDGE_INSETS * 2);
CGFloat radius = diameter / 2;
CGPoint center = CGPointMake(width / 2, height / 2);
// Create the image context
UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0);
// Create the bezier paths
UIBezierPath *clipPath = [UIBezierPath bezierPathWithRect:bounds];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(center.x - radius, center.y - radius, diameter, diameter)];
[clipPath appendPath:maskPath];
clipPath.usesEvenOddFillRule = YES;
[clipPath addClip];
[[UIColor colorWithWhite:0 alpha:0.5f] setFill];
[clipPath fill];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage;
}
我基本上创建了一个我在图像scrollView上面添加的子视图,如下所示:
UIImageView *maskView = [[UIImageView alloc] initWithImage:[self overlayMask]];
maskView.userInteractionEnabled = NO;
[self.view insertSubview:maskView aboveSubview:_scrollView];
希望有所帮助。
(最初见于DZNPhotoPickerController)