3

我正在开发一个 iphone 应用程序,我想创建一个具有多种颜色的圆圈。如下图

在此处输入图像描述

m 使用 draw rect 方法绘制一个圆圈,但没有多种颜色的运气。

你能帮我么?

提前致谢。

4

2 回答 2

5

您可以使用带有圆形蒙版的CAGradientLayer来实现此效果。示例代码(假设您在某些视图控制器中使用它):

- (void)viewDidLoad
{
    [super viewDidLoad];

    CAGradientLayer *glayer = [CAGradientLayer layer];
    glayer.frame = CGRectMake(60.0f, 60.0f, 200.0f, 200.0f);
    glayer.colors = @[(__bridge id)[UIColor greenColor].CGColor,
                      (__bridge id)[UIColor cyanColor].CGColor,
                      (__bridge id)[UIColor blueColor].CGColor,
                      (__bridge id)[UIColor purpleColor].CGColor,
                      (__bridge id)[UIColor redColor].CGColor,
                      (__bridge id)[UIColor orangeColor].CGColor,
                      (__bridge id)[UIColor yellowColor].CGColor];
    glayer.backgroundColor = [UIColor redColor].CGColor;
    CAShapeLayer *shLayer = [CAShapeLayer layer];
    [shLayer setPath:CGPathCreateWithEllipseInRect(CGRectMake(0, 0, 200, 200), NULL)];
    [glayer setMask:shLayer];
    [self.view.layer addSublayer: glayer];
}

请注意,CAGradientLayer 的colors和属性是可动画的,因此您可以使用该方法轻松添加动画效果locations

于 2013-11-14T06:27:26.427 回答
2

您可以尝试使用 QuartzCore 中的 CGGradientRef 和 CGContextDrawLinearGradient(不要忘记将 QuartzCore 添加到您的项目并导入它)

创建渐变您可以使用类似的东西(在 UIView 子类中):

- (void)drawRect:(CGRect)rect
{
        CGContextRef ctx = UIGraphicsGetCurrentContext();

        CGGradientRef gradient;
        CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();;

        //5 is for count of colors
        CGFloat parts[5] = { .2, .4, .6, .8, .1 };

        //colors for each part, so 5 parts by 4 each (r,g,b,a for each part in range 0 - 1, 1 is for 255 in regular rgb space, and alpha as usual)
        CGFloat components[20] = {
            .3, .24, .1, 1,
            .3, .2, .7, 1,
            .3, .84, .2, 1,
            .3, .24, .3, 1,
            .1, .5, .38, 1
        };

        gradient = CGGradientCreateWithColorComponents(rgb, components, parts, 5);

        CGPoint top = CGPointMake(CGRectGetMidX(rect), 0.0f);
        CGPoint bottom = CGPointMake(CGRectGetMidX(rect), rect.size.height);

        CGContextDrawLinearGradient(ctx, gradient, top, bottom, 0);

        CGGradientRelease(gradient);
        CGColorSpaceRelease(rgb);

        //round shape you can archive by Vladimir's solution
        CAShapeLayer *shLayer = [CAShapeLayer layer];
        [shLayer setPath:CGPathCreateWithEllipseInRect(CGRectInset(rect, 5, 5), NULL)];
        [self.layer setMask:shLayer];
}
于 2013-11-14T06:42:01.423 回答