我有自定义UIView
。当手指触摸移动时,我会保持线条和点。然后我用这个方法给CGPath
指点:
- (void)makeCGPath
{
CGMutablePathRef path = CGPathCreateMutable();
if (lines&& lines.count>0)
{
for (int i = 0; i < lines.count; i++)
{
CGMutablePathRef linePath = CGPathCreateMutable();
NSArray *tempArray = [lines objectAtIndex:i];
CGPoint p = [[tempArray objectAtIndex:0]CGPointValue];
CGPathMoveToPoint(linePath, NULL, p.x, p.y);
for (int j = 1; j < tempArray.count; j++)
{
p = [[tempArray objectAtIndex:j]CGPointValue];
CGPathAddLineToPoint(linePath, NULL, p.x, p.y);
}
CGPathAddPath(path, NULL, linePath);
CGPathRelease(linePath);
}
}
if (points&& points.count > 0)
{
CGMutablePathRef pointPath = CGPathCreateMutable();
CGPoint p = [[points objectAtIndex:0]CGPointValue];
CGPathMoveToPoint(pointPath, NULL, p.x, p.y);
for (int i = 1; i < points.count;i++ )
{
p = [[points objectAtIndex:i]CGPointValue];
CGPathAddLineToPoint(pointPath, NULL, p.x, p.y);
}
CGPathAddPath(path, NULL, pointPath);
CGPathRelease(pointPath);
}
drawPath = CGPathCreateCopy(path);
[self setNeedsDisplay];
[lines removeAllObjects];
[points removeAllObjects];
}
我的drawRect如下所示。
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 3);
[[UIColor blackColor]set];
CGContextAddPath(ctx, drawPath);
CGContextStrokePath(ctx);
}
它似乎很奇怪,它只显示屏幕上的最后一行。怎么了?
如何在屏幕上保留所有这些路径?
答案 0 :(得分:3)
我有完全相同的问题。它不适用于iOS 5.0,但它适用于iOS 5.1及更高版本。我还在寻找修复。
UPADTE: 我使用UIBezierPath修复了这个问题。您可以使用Besier绘制所有路径,然后以这种方式将其转换为CGPath:
UIBezierPath *path = [[UIBezierPath alloc] init];
// Add all the lines you need
[path addLineToPoint:p];
// Or points
[path moveToPoint:p];
// Append paths
[path appendPath:linePath];
// Make a CGPath from UIBezierPath
CGPath myCGPath = path.CGPath;
尝试使用此代码,它应该可以工作,但我还没有测试过:
- (void)makeCGPath
{
UIBezierPath *path = [[UIBezierPath alloc] init];
if (lines && lines.count>0)
{
for (int i = 0; i < lines.count; i++)
{
UIBezierPath *linePath = [[UIBezierPath alloc] init];
NSArray *tempArray = [lines objectAtIndex:i];
CGPoint p = [[tempArray objectAtIndex:0]CGPointValue];
[linePath addLineToPoint:p];
for (int j = 1; j < tempArray.count; j++)
{
p = [[tempArray objectAtIndex:j]CGPointValue];
[linePath addLineToPoint:p];
}
[path appendPath:linePath];
}
}
if (points && points.count > 0)
{
UIBezierPath *pointPath = [[UIBezierPath alloc] init];
CGPoint p = [[points objectAtIndex:0]CGPointValue];
[pointPath moveToPoint:p];
for (int i = 1; i < points.count;i++ )
{
p = [[points objectAtIndex:i]CGPointValue];
[pointPath moveToPoint:p];
}
[path appendPath:pointPath];
}
drawPath = path.CGPath;
[self setNeedsDisplay];
[lines removeAllObjects];
[points removeAllObjects];
}