2011-01-12 103 views
2

嘿客觀的C IM初學者請幫我如何在觸摸事件上畫線?

我把下面的代碼,但不能正常工作.....

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

UITouch *touch = [touches anyObject]; 
if ([touch view] == self.view) { 

    CGPoint location = [touch locationInView:self.view]; 
    loc1 = location; 
    CGContextMoveToPoint(context, location.x, location.y); 
    NSLog(@"x:%d y:%d At Touch Begain", loc1.x, loc1.y); 
} 
} 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 

{ 
    UITouch *touch = [touches anyObject]; 

     if ([touch view] == self.view) 
    { 
    CGPoint location = [touch locationInView:self.view]; 
    CGContextMoveToPoint(context, loc1.x, loc1.y); 
    NSLog(@"x:%d y:%d At Touch Move", loc1.x, loc1.y); 
    CGContextAddLineToPoint(context, location.x, location.y); 
    NSLog(@"x:%d y:%d", location.x, location.y); 
} 

} 

我在viewDidLoad方法聲明CONTEX也嘗試聯繫事件申報但不工作...

我的應用程序日誌文件的樣子......

X:0 Y:1079934976在觸摸移動週四1月13日11點20分05秒。當地 的DragDrop [536 ]:

CGContextAddLineToPoint:無效的上下文爲0x0 2011-01-13 11:20:05.149 的DragDrop [536:207]×:0 Y:1079902208週四年01月13 11點20分05秒。本地 的DragDrop [536]:

CGContextSetRGBStrokeColor:無效的上下文爲0x0週四年01月13 11點20分05秒 。本地的DragDrop [536]:

CGContextDrawPath:無效的上下文爲0x0週四年01月13 11點20分05秒。本地 的DragDrop [536]:

CGContextMoveToPoint:invalid context 0x0 2011-01-13 11:20:0 5.199 的DragDrop [536:207]×:0 Y:1079934976在觸摸移動星期四年01月13 11點20分05秒 。本地的DragDrop [536]:

CGContextAddLineToPoint:無效的上下文爲0x0 2011-01-13 11:20 :05.200 的DragDrop [536:207]×:0 Y:1079885824

回答

13

您通常不直接繪製觸摸檢測方法。 通常,您只需在那裏存儲新的點/線,並在drawRect:中繪製所有點。假設您有一個自定義子類UIView,它具有NSMutableArray類型的實例變量pathsUIBezierPath類型的屬性currentPath。然後,您可以大致如下實現觸摸檢測和drawRect方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    self.currentPath = [UIBezierPath bezierPath]; 
    currentPath.lineWidth = 3.0; 
    [currentPath moveToPoint:[touch locationInView:self]]; 
    [paths addObject:self.currentPath]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    [self.currentPath addLineToPoint:[touch locationInView:self]]; 
    [self setNeedsDisplay]; 
} 

- (void)drawRect:(CGRect)rect { 
    [[UIColor redColor] set]; 
    for (UIBezierPath *path in paths) { 
    [path stroke]; 
    } 
} 

請注意,這被簡化了很多。如果繪製很多線條,性能會受到影響,最終,您需要將圖形緩存在位圖圖像中,但這應該讓您開始。

0

您需要AddLineToPoint一個電話後,打電話給CGContextStrokePath。 請確保先定義筆觸路徑顏色。

CGContextSetRGBStrokeColor(context,0,0,1,1); 
CGContextStrokePath(context);