Hexagon with different colors iOS

时间:2015-11-18 21:01:13

标签: ios objective-c uibezierpath cashapelayer

I am trying to make a hexagon progress with different colors. I created a hexagon shape but i couldn't give different colors for each lines. Is there any way to do that? Also can i change first 2 line colors after passed these are?

Here is my code;

- (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"];

}

Thanks for your help and interest.

1 个答案:

答案 0 :(得分:0)

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