问题描述
我知道 CAGradientLayer
目前不支持径向渐变,只能选择 kCAGradientLayerAxial
。
I know CAGradientLayer
doesn't support radial gradient at the moment and only has option of kCAGradientLayerAxial
.
我想要如下所示:
我已经四处寻找这个问题并发现有一种解决方法。但这些解释对我来说并不清楚。所以我想知道我是否可以使用 CAGradientLayer
绘制径向渐变,如果是,那么怎么做呢?
I have looked around for this issue and found that there is a way around this. But the explanations were not clear to me. So I want to know if I can draw radial gradients using CAGradientLayer
and if so, then how to do it?
推荐答案
根据我的理解,你只需要一个绘制渐变的图层, CGContextDrawRadialGradient
可以完美地满足这种需要。并重申你所说的, CAGradientLayer
不支持径向渐变,我们无能为力,除了可以用<$ c干净地完成的不必要的调整$ c> CALayer 子类。
From what I understood, you just need a layer that draws a gradient, and CGContextDrawRadialGradient
works perfectly for that need. And to reiterate on what you said, CAGradientLayer
doesn't support radial gradients, and nothing we can do about that, except unnecessary swizzling that can be done cleanly with a CALayer
subclass.
(注意:渐变绘图代码。这不是这个答案的内容。)
(note: the gradient drawing code was taken from here. It isn't what this answer is about.)
viewDidLoad
:
GradientLayer *gradientLayer = [[GradientLayer alloc] init];
gradientLayer.frame = self.view.bounds;
[self.view.layer addSublayer:gradientLayer];
CALayer
子类:
- (instancetype)init
{
self = [super init];
if (self) {
[self setNeedsDisplay];
}
return self;
}
- (void)drawInContext:(CGContextRef)ctx
{
size_t gradLocationsNum = 2;
CGFloat gradLocations[2] = {0.0f, 1.0f};
CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
CGColorSpaceRelease(colorSpace);
CGPoint gradCenter= CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
CGFloat gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;
CGContextDrawRadialGradient (ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient);
}
这篇关于如何在CALayer中绘制径向渐变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!