2017-02-02 48 views
0

我想创建一个径向渐变蒙版以在图片中创建一个洞,以便您可以看透图片。我创建了一个覆盖图像与孔和下方的形象是可见的,如下图所示:创建一个径向渐变蒙版以在图片中创建一个洞

enter image description here

我能够创建一个使用CGImageMaskCreate()成功这一形象。但由于iOS 10.0中的CGImageMaskCreate()的不寻常行为,我正在寻找其他解决方案。

一个这样的解决方案是使用UIView的maskView属性创建图像蒙板。我能够使用maskView编写用于创建上述图像效果的代码。但它没有给出正确的结果。

我不是很擅长Core Graphics,也许这就是为什么我无法弄清楚自己出错的原因。我的代码是:

CGRect rect = CGRectMake(0.0, 0.0, self.view.bounds.size.width, self.view.bounds.size.height); 
CGSize size = self.view.bounds.size; 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGFloat radius = 160.0; 
CGPoint center = CGPointMake(150.0, 150.0); 
CGFloat components[] = {1.0,1.0,1.0,1.0, 1.0,1.0,1.0,1.0, 1.0,1.0,1.0,1.0,  1.0,1.0,1.0,1.0, 1.0,1.0,1.0,0.5, 1.0,1.0,1.0,0.0}; 
CGFloat locations[] = {0.0, 0.1, 0.2, 0.8, 0.9, 1.0}; 

//creating bitmap context 
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrder32Big); 
//creating gradient 
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, 6); 
CGContextDrawRadialGradient(context, gradient, center, 0.1, center, radius, 0); 
//get the gradient image 
CGImageRef imageHole = CGBitmapContextCreateImage(context); 
UIImage *img = [UIImage imageWithCGImage:imageHole]; 
CGGradientRelease(gradient); 

//creating mask view whose alpha channels will be used for masking 
UIImageView *maskImgView = [[UIImageView alloc] initWithFrame:CGRectMake(50.0, 50.0, 100.0, 100.0)]; 
[maskImgView setImage:img]; 

//This is the view on which I want to perform masking 
UIImageView *mainView = [[UIImageView alloc] initWithFrame:self.view.bounds]; 
[mainView setImage:[UIImage imageNamed:@"insta-logo.png"]]; 
mainView.maskView = maskImgView; 
[self.view addSubview:mainView]; 

这个结果我得到:

enter image description here

使用完全充满了红色的图像。我希望生成的图像在渐变区域中是透明的,这样您就可以通过它,并且我希望区域的其余部分保持红色,以保留其余图像的不透明度,就像我张贴的第一张图片一样。

我想使用maskView属性创建此效果,因为在iOS 10及更高版本中遇到了CAShapeLayerCGImageMaskCreate()的异常行为。

任何建议将会非常有帮助。 谢谢。

+0

“在iOS 10及更高版本中遇到的CAShapeLayer和CGImageMaskCreate()的异常行为”您究竟指什么? – matt

+0

使用CGImageMaskCreate()可以正确创建遮罩,但最终的遮罩图像几乎是透明的。对于我的应用程序,这个问题只发生在iPhone 7及以上。我想这是因为与iOS 10的一些问题。 – maven25

+0

顺便说一下,我从这个线程得到了一些帮助https://forums.developer.apple.com/thread/50854 – maven25

回答

0

我想你描述是这样的:

enter image description here

正如你所看到的,我打了个径向渐变孔在图像视图,允许黄色背景显示通过。

那是怎么做的?这是一个带有清晰和黑色颜色值的CIFilter("CIRadialGradient"),用作图像视图的mask

+0

_your_代码的问题在于,您的渐变中没有清晰的中心;而不是从一个清晰的中心消失到一个黑色的外面,你从一个黑色的中心褪色到一个清晰的外部。实际上,您的颜色数组“组件”是向后的 - 就这些。修复这个问题,你的代码可以正常工作。我可能会这样做,但是你的方式提供了更精确的控制,所以请立即行事并按照你的方式去做。 – matt