简单绘制连续多个五角星

以下代码由本人经过几天的苦思冥想,才做出,希望广大读者认真阅读!

-(void)drawRect:(CGRect)rect{
    //获取绘图的CGContextRef
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    int num = [self.starNumber intValue];
    int y = 0;
    int x = 50;
    //开始添加路径
    CGContextBeginPath(ctx);
    for (int i =0; i< num ;i++) {
        if (i % 4 == 0) {
            y += 100;
            x = 50;
        }
        //添加五角星的路径
        [self CGContextAddStar:ctx starCount:5 starX:x starY:y starSize:50];
        x += 100;
    }
    //填充颜色
    CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
    //
    CGContextStrokePath(ctx);
    //关闭路径
    CGContextClosePath(ctx);
}

-(void)CGContextAddStar:(CGContextRef)c starCount:(NSInteger)n starX:(CGFloat)dx starY:(CGFloat)dy starSize:(NSInteger)size{
    CGFloat dig = 4* M_PI / n ;
    // 移动到指定点
    CGContextMoveToPoint(c , dx , dy + size);
    for(int i = 1 ; i <= n ; i++)
    {
        CGFloat x = sin(i * dig);
        CGFloat y = cos(i * dig);
        // 绘制从当前点连接到指定点的线条
        CGContextAddLineToPoint(c , x * size + dx ,y * size + dy);
    }
}


你可能感兴趣的:(简单绘制连续多个五角星)