不同颜色的六边形 iOS

Hexagon with different colors iOS

我正在尝试用不同的颜色进行六边形进度。我创建了一个六边形,但我无法为每条线提供不同的颜色。有什么办法吗?我也可以在通过这些之后更改前 2 行颜色吗?

这是我的代码;

- (void)drawRect:(CGRect)rect
{

float polySize = self.frame.size.height/2;

CGFloat hexWidth = self.frame.size.width;
CGFloat hexHeight = self.frame.size.height;

CGPoint center;

//Start drawing polygon
center = CGPointMake(hexWidth/2, hexHeight/2);
NSLog(@"center x = %f",center.x);

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(center.x, 0)];
NSLog(@"center x = %f --- center y = %f",center.x,center.y + 100);

for(int i = 3; i >= 0 ; i--)
{

    CGFloat x = polySize * sinf(i * 2.0 * M_PI / 6);
    CGFloat y = polySize * cosf(i * 2.0 * M_PI / 6);

    NSLog(@"x = %f --- y = %f",center.x + x,center.y + y);

    //CGContextAddLineToPoint(context, center.x + x, center.y + y);
    [path addLineToPoint:CGPointMake(center.x + x, center.y + y)];

}

for(int i = 6; i >= 3 ; i--)
{

    CGFloat x = polySize * sinf(i * 2.0 * M_PI / 6);
    CGFloat y = polySize * cosf(i * 2.0 * M_PI / 6);

    NSLog(@"x = %f --- y = %f",center.x + x,center.y + y);

    //CGContextAddLineToPoint(context, center.x + x, center.y + y);
    [path addLineToPoint:CGPointMake(center.x + x, center.y + y)];

}

CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.bounds;
pathLayer.path = path.CGPath;
pathLayer.lineCap = kCALineCapRound;

pathLayer.strokeColor = [[UIColor blackColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 10.0f;
pathLayer.cornerRadius = 5.0f;
pathLayer.lineJoin = kCALineJoinBevel;
//pathLayer.lineDashPattern = @[@10];

[self.layer addSublayer:pathLayer];

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 0.8;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

}

感谢您的帮助和关注。

一个形状图层全部用一种颜色绘制。使用 CGGraphics 绘制的 UIBezierPath 也是如此。如果你想使用混合颜色,你要么需要从多个形状层构建它,要么在自定义 drawRect 中使用多个绘制命令。