2016-12-28 100 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