循环CAGradientLayer面具 – iOS

我在我的图片上使用CAGradientLayer 。 我使用这个代码来做到这一点:

 UIImage *image = [UIImage imageNamed:@"perfect.jpg"]; [testImage setImage:image]; CAGradientLayer *myLayer = [CAGradientLayer layer]; myLayer.anchorPoint = CGPointZero; //starts in bottom left myLayer.startPoint = CGPointMake(1.0f,1.0f); //ends in top right myLayer.endPoint = CGPointMake(1.0f, 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]; 

但是我想要的是一个径向渐变或圆梯度效果。 我只是在一边渐变。 我怎样才能实现一个圆形渐变层? 谢谢。

如果你想要一个圆形的渐变图层,你将不得不- (void)drawInContext:(CGContextRef)ctx和重写- (void)drawInContext:(CGContextRef)ctx方法。 在这个代码是非常简单的,应该看起来像这样的径向渐变:

  CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); NSArray* colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor blackColor].CGColor]; CGFloat locations[] = {.25, .75}; CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations); CGPoint center = (CGPoint){self.bounds.size.width / 2, self.bounds.size.height / 2}; CGContextDrawRadialGradient(ctx, gradient, center, 20, center, 40, kCGGradientDrawsAfterEndLocation); CGGradientRelease(gradient); CGColorSpaceRelease(colorSpace); 

请注意,我现在无法testing代码,但应该没问题。 如果不是径向渐变,你需要一个像这样的angular度渐变:

在这里输入图像说明

由于Objective c无法直接完成,所以你很倒霉。 要做到这一点,你可以循环通过所需的颜色之间的线性插值,并直接绘制它们(不难实现,但性能较差)或使用图像作为蒙版。