我该如何在iOS上绘制嵌套的径向渐变?

3

我正在使用最新的SDK开发一个iOS 5.0+应用程序。

我想做类似于下面这个图像的东西

Figure 8-6

我想知道如何嵌套径向渐变。

这是我的代码:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    _innerColor = [UIColor yellowColor];
    _outerColor = [UIColor redColor];

    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    
    CGFloat graWidth = layer.frame.size.width / 2;
    CGFloat graHeight = layer.frame.size.height / 2;

    CGFloat firstGlossLocation = 0.0f;
    CGFloat outterPercent = 0.0f;
    
    if (_isUnSelected)
    {
        firstGlossLocation = 0.7f;
        outterPercent = graWidth * 0.0f;
    }
    else
    {
        firstGlossLocation = 0.0f;
        outterPercent = graWidth * 0.25f;
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    CGFloat iRed = 0.0, iGreen = 0.0, iBlue = 0.0, iAlpha =0.0;
    [_innerColor getRed:&iRed green:&iGreen blue:&iBlue alpha:&iAlpha];
    
    CGFloat oRed = 0.0, oGreen = 0.0, oBlue = 0.0, oAlpha =0.0;
    [_outerColor getRed:&oRed green:&oGreen blue:&oBlue alpha:&oAlpha];
    
    CGFloat gradientColors[] = {
        oRed, oGreen, oBlue, oAlpha,
        iRed, iGreen, iBlue, iAlpha
    };
    
    // We have to change first value when user taps over the Guage.
    // The second one must one to fill the entire Gauge.
    CGFloat glossLocations[] = {firstGlossLocation, 1};
    CGGradientRef ballGradient = CGGradientCreateWithColorComponents(colorSpace, gradientColors, glossLocations, 2);
    
    CGContextAddEllipseInRect(context, CGRectMake(0, 0, graWidth*2, graHeight*2));
    CGContextClip(context);
    
    CGPoint startPoint = CGPointMake(graWidth, graHeight);
    CGPoint endPoint = CGPointMake(graWidth, graHeight);
    CGContextDrawRadialGradient(context, ballGradient, startPoint, 0, endPoint, graWidth - outterPercent, kCGGradientDrawsAfterEndLocation);
    CGContextDrawPath(context, kCGPathStroke);
}

_isUnSelectedNO时,我希望绘制第二个渐变。

您知道如何绘制第二个嵌套渐变吗?


1
感谢您的投票并告诉我为什么这样做。 - VansFannel
1
这是一个奇怪的踩票。有什么问题吗? - matt
1
+1 对于一个有趣的问题 - rog
1个回答

4
您不需要在您的插图中使用“第二个嵌套渐变”来绘制所示的渐变效果。这是一个渐变效果,可以在多个位置拥有多种颜色,这就是我们在这个插图中看到的情况。它似乎有四种颜色/点。
因此,当需要更改图像时,请用包含四种颜色/点的第二个渐变替换第一个简单的双点渐变,并反之亦然。

谢谢您的回答。您有任何示例我可以跟随来做吗? - VansFannel
2
你自己的代码很棒,你已经写了自己的示例。唯一的区别是你有一个2元素的glossLocations数组(和一个8元素的gradientColor数组与之相配)。只需将其更改为4元素的glossLocations数组(和一个16元素的gradientColor数组),你就完成了。Badda bing badda boom. - matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接