3

我正在尝试使用循环来构建可变数量的 CGMutablePathRef,以便在圆上绘制可变数量的填充楔形。但是,出于某种原因,在循环结束时,我的数组仅返回一个对象。这是我用来构造数组的方法:

+ (NSMutableArray *)pathForCircleWithRect:(CGRect)rect numOfWedges:(NSUInteger)num
{
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
CGFloat radius = rect.size.width / 2;
CGFloat angle = RADIANS(360) / num;

CGFloat startAngle = 0;
CGFloat endAngle = startAngle + angle;

NSMutableArray *paths = [NSMutableArray array];

for (int x = 0; x < num; x++);
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, center.x, center.y);
    CGPathAddArc(path, NULL, center.x, center.y, radius, startAngle, endAngle, 0);
    CGPathAddLineToPoint(path, NULL, center.x, center.y);

    [paths addObject:(id)path];
    startAngle = endAngle;
    endAngle = startAngle + angle;
}

return paths;
}

编辑 使用 UIBezierPath 的新尝试:

+ (NSMutableArray *)pathForCircleWithRect:(CGRect)rect numOfWedges:(NSUInteger)num
{
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
CGFloat radius = rect.size.width / 2;
CGFloat angle = RADIANS(360) / num;

CGFloat startAngle = 0;
CGFloat endAngle = startAngle + angle;

NSMutableArray *paths = [NSMutableArray array];

for (int x = 0; x < num; x++);
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, center.x, center.y);
    CGPathAddArc(path, NULL, center.x, center.y, radius, startAngle, endAngle, 0);
    CGPathAddLineToPoint(path, NULL, center.x, center.y);

    [paths addObject:[UIBezierPath bezierPathWithCGPath:path]];
    startAngle = endAngle;
    endAngle = startAngle + angle;
}

return paths;
}

调用此函数的代码:

- (void)drawRect:(CGRect)rect
{
int num = 18;
NSMutableArray *paths = [WheelView pathForCircleWithRect:rect numOfWedges:num];
NSMutableArray *colors = [WheelView colorsForCircleWithNumOfWedges:num];
CGContextRef context = UIGraphicsGetCurrentContext();

for (int x = 0; x < num; x++)
{
    CGContextSetFillColorWithColor(context, (CGColorRef)[colors objectAtIndex:x]);
    CGContextSaveGState(context);
    CGMutablePathRef wedgePath = (CGMutablePathRef)[paths objectAtIndex:x];
    CGContextAddPath(context, wedgePath);
    CGContextDrawPath(context, kCGPathFill);
    //CGContextClip(context);
    CGContextRestoreGState(context);
}
}
4

1 回答 1

1

这个问题的答案比内存泄漏要简单得多,尽管内存泄漏无疑会导致未来的问题。我的代码根本无法运行,因为我不小心在行尾放置了一个分号for,所以for循环甚至没有运行。

于 2012-01-03T17:42:55.957 回答