【发布时间】:2011-09-11 09:36:22
【问题描述】:
我正在尝试使用循环来构建可变数量的 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);
}
}
【问题讨论】:
-
两个 cmets:1) 你正在泄漏路径。您正在创建它们,然后将它们添加到数组中,然后不释放。 2) CGPathRef 不是与任何Objective-C 对象免费桥接的。事实上,它们很有可能会起作用,因为 CFTypeRefs 使用的基类将
-retain转换为CFRetain(),但严格来说,它不应该。你应该用UIBezierPath*对象包裹你的CFPathRefs。 -
你真的用
numOfWedges:> 1 调用方法吗? -
是的,我用 18 输入它。我在循环中插入断点以确保 x 确实达到 18。返回的对象只是第一个路径。
-
@Kevin Ballard 是的,我认为泄露路径比发现我过早发布它们更好。实际上,当我将它们从数组中拉出时,我只是将这些路径直接转换回 CGMutablePathRef ......有没有更好的数组包装器我可以在那里使用?
-
@Kevin Ballard 我试图将路径包装在
UIBezierPath对象中,但我仍然遇到同样的问题。我已经用新代码更新了问题。
标签: iphone ios4 core-graphics cgpath