2016-12-28 101 views
0

我是新来的iOS和目标c,我正在开发一个应用程序,我想绘制连续的曲线,如下图所示。这里是我的代码,但它仅绘制单staright线..如何在核心图形中连续绘制曲线ios

- (void)drawRect:(CGRect)rect{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // set the line properties 
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
    CGContextSetLineCap(context, kCGLineCapRound); 
    CGContextSetLineWidth(context, 30); 
    CGContextSetAlpha(context, 0.6); 

    // draw the line 
    CGContextMoveToPoint(context, startPoint.x, startPoint.y); 
    CGContextAddLineToPoint(context, endPoint.x, endPoint.y); 
    CGContextStrokePath(context); 
} 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint current = [touch locationInView:self]; 
    startPoint=current; 
    arrPoints=[[NSMutableArray alloc]init]; 
    [arrPoints addObject:NSStringFromCGPoint(startPoint)]; 
} 

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint p = [touch locationInView:self]; 

    endPoint=p; 
    [arrPoints addObject:NSStringFromCGPoint(endPoint)]; 
    [self setNeedsDisplay]; 
} 

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
    [self touchesMoved:touches withEvent:event]; 
} 

这里就是我想实现是假设有五种观看图片,我想继续画线从开始首先以第二,第三,等等,并在同一时间,我想在每行以绘制曲线..

enter image description here

回答

1

你的代码已经建设点的数组。

现在您需要修改drawRect方法来绘制所有点之间的线段,而不仅仅是最新的点。

如果您从线段中创建UIBezierPath并一次绘制,您可能会获得更好的性能。

这样的结果将是一系列连续的短线段,它们近似于曲线。如果用户快速移动他的手指,则线段会变长,从而使曲线看起来更加不连贯。

一旦你得到那个工作,有一些技巧可以用来平滑生成的曲线。 Erica Sadun出色的“Core iOS Developer's Cookbook”有一个名为“Smoothing”的配方,涵盖了这个话题。它完全符合你的要求 - 通过用户进行徒手绘制并使其平滑。

我在Github上有几个项目使用Erica Sadun的线条平滑技术。

该项目KeyframeViewAnimations绘制一条曲线,通过一组预定义点。

项目“RandomBlobs”绘制了一条闭合曲线,该曲线是多边形的平滑版本。

这两个都包括Sadun博士的曲线平滑代码,但是她的书中的章节再次适合您的需求。

+0

我想实现的是假设有五个视图,我开始从一个视图进行绘制,并将线移动到另一个视图,在第二个视图中,我想绘制手指在哪个方向移动的曲线 – IMakk

+1

根据您的描述, Erica Sadun的“核心iOS开发者的食谱”在配方“平滑图画”中正是你想要的。它使用称为Catmull-Rom样条的技术,从用户用手指画出的点创建平滑曲线。我建议买这本书。它充满了像那样的宝石,而且一本“配方”是值得本书的价格,因为它完全符合你的要求。 –

+0

感谢您的回复。 – IMakk