ios - Transparent radial Gradient Layer Mask

不羁的心 提交于 2020-01-03 06:05:10

问题


I'm using a CAGradientLayer to as a layer to my image. Im using this code:

UIImage *image = [UIImage imageNamed:@"perfect.jpg"];

[testImage setImage:image];

CAGradientLayer *myLayer = [CAGradientLayer layer];

myLayer.anchorPoint = CGPointZero;

//starts in bottom left
myLayer.startPoint = CGPointMake(0.0f,0.5f);

//ends in top right
myLayer.endPoint = CGPointMake(0.5f, 0.0f);

UIColor *outerColor = [UIColor colorWithWhite:1.0 alpha:0.0];
UIColor *innerColor = [UIColor colorWithWhite:1.0 alpha:1.0];

//an array of colors that dictatates the gradient(s)
myLayer.colors = @[(id)outerColor.CGColor, (id)outerColor.CGColor, (id)innerColor.CGColor, (id)innerColor.CGColor];

//these are percentage points along the line defined by our startPoint and endPoint and correspond to our colors array. The gradient will shift between the colors between these percentage points.
myLayer.locations = @[@0.0, @0.15, @0.5, @1.0f];

myLayer.bounds = CGRectMake(0, 0, CGRectGetWidth(testImage.bounds), CGRectGetHeight(testImage.bounds));

testImage.layer.mask = myLayer;

[self.view addSubview:testImage];

But the gradient is only applied on sides of my image. What I want is to apply the gradient as circle or a radial gradient. How can I do this?


回答1:


You can get the radial gradient by using CIFilter with name CIVignette. Try using the below code.

UIImage *image = [UIImage imageNamed:@"perfect.jpg"];
CIFilter *vignette = [CIFilter filterWithName:@"CIVignette"];
[vignette setValue:image forKey:kCIInputImageKey];
[vignette setValue:@(1) forKey:@"inputIntensity"];
[vignette setValue:@(30) forKey:@"inputRadius"];

CIImage *outputImage = [vignette outputImage];
CGImageRef cgimg = [ [CIContext contextWithOptions:nil] createCGImage:outputImage
                                 fromRect:[outputImage extent]];
UIImage *newImage = [UIImage imageWithCGImage:cgimg];
testImage.image = newImage;
[self.view addSubview:testImage];

For more information u can refer this tutorial.



来源:https://stackoverflow.com/questions/23494063/ios-transparent-radial-gradient-layer-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!