2011-11-14 87 views
1

我希望能夠使用UIBezierPath在我的iPad屏幕上繪製直線。我會怎麼做呢?如何使用UIBezierPath繪製平滑的直線?

我想要做的是這樣的:我在屏幕上雙擊來定義起點。一旦我的手指在屏幕上方,直線就會隨着我的手指移動(這應該發生在我應該把我的下一個手指放在哪裏,以便它會創建一條直線)。然後,如果我再次在屏幕上雙擊,則會定義終點。

此外,如果我雙擊結束點,則應該開始新行。

是否有任何可用於指導的資源?

+2

在投票時進行某種解釋是一種常態。 – ryanprayogo

+0

@raaz一旦停止接觸玻璃杯,您將無法跟蹤用戶的手指。那麼,除非你用相機實現一些少數民族報告式的神奇魔力,但我認爲這是不值得的巨大努力。其餘部分很容易實現:只需將'UITouch'信息導入@ StuDev的答案(UIBezierPath'的要點)。 –

回答

8
UIBezierPath *path = [UIBezierPath bezierPath]; 
[path moveToPoint:startOfLine]; 
[path addLineToPoint:endOfLine]; 
[path stroke]; 

UIBezierPath Class Reference

編輯

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Create an array to store line points 
    self.linePoints = [NSMutableArray array]; 

    // Create double tap gesture recognizer 
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)]; 
    [doubleTap setNumberOfTapsRequired:2]; 
    [self.view addGestureRecognizer:doubleTap]; 
} 

- (void)handleDoubleTap:(UITapGestureRecognizer *)sender 
{ 
    if (sender.state == UIGestureRecognizerStateRecognized) { 

     CGPoint touchPoint = [sender locationInView:sender.view]; 

     // If touch is within range of previous start/end points, use that point. 
     for (NSValue *pointValue in linePoints) { 
      CGPoint linePoint = [pointValue CGPointValue]; 
      CGFloat distanceFromTouch = sqrtf(powf((touchPoint.x - linePoint.x), 2) + powf((touchPoint.y - linePoint.y), 2)); 
      if (distanceFromTouch < MAX_TOUCH_DISTANCE) { // Say, MAX_TOUCH_DISTANCE = 20.0f, for example... 
       touchPoint = linePoint; 
      } 
     } 

     // Draw the line: 
     // If no start point yet specified... 
     if (!currentPath) { 
      currentPath = [UIBezierPath bezierPath]; 
      [currentPath moveToPoint:touchPoint]; 
     } 

     // If start point already specified... 
     else { 
      [currentPath addLineToPoint:touchPoint]; 
      [currentPath stroke]; 
      currentPath = nil; 
     } 

     // Hold onto this point 
     [linePoints addObject:[NSValue valueWithCGPoint:touchPoint]]; 
    } 
} 

我不能沒有金錢補償編寫任何少數派報告式的攝像頭魔碼。

+0

@ studdev,我已經添加了一些進一步的解釋我想做什麼 – raaz