gpt4 book ai didi

ios - 圆形 CAGradientLayer 蒙版 - iOS

转载 作者:行者123 更新时间:2023-11-28 17:53:27 25 4
gpt4 key购买 nike

我在图像上使用 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 方法。因为代码非常简单,对于径向渐变应该看起来像这样:

        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);

请注意,我现在无法测试代码,但应该没问题。如果您想要像这样的角度渐变而不是径向渐变:

enter image description here

你很不幸,因为 Objective c 没有办法直接实现它。要做到这一点,您可以循环遍历所需颜色之间的线性插值并直接绘制它们(实现起来并不难,但性能不佳)或使用图像作为 mask 。

关于ios - 圆形 CAGradientLayer 蒙版 - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23487661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com