我正在开发一款iphone应用程序,我想创建一个多色的圆圈。如下图所示
使用draw rect方法绘制一个圆圈,但没有多分数的运气。
你能帮我吗?提前致谢。
答案 0 :(得分: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
属性是可动画的,因此您可以使用该方法轻松添加动画效果
答案 1 :(得分: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];
}