如何在触摸事件上绘制线条?

时间:2011-01-12 13:50:16

标签: iphone objective-c ios4

嘿,我是目标C的初学者,请帮帮我

我制作以下代码,但没有工作......

-(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在Touch Move Thu 1月13日11:20:05 .local   DragDrop [536]:

     

CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.149   DragDrop [536:207] x:0 y:1079902208 Thu Jan 13 11:20:05 .local   DragDrop [536]:

     

CGContextSetRGBStrokeColor:无效的上下文0x0 Thu Jan 13 11:20:05   .local DragDrop [536]:

     

CGContextDrawPath:无效的上下文0x0 Thu Jan 13 11:20:05 .local   DragDrop [536]:

     

CGContextMoveToPoint:无效的上下文0x0 2011-01-13 11:20:05.199   DragDrop [536:207] x:0 y:1079934976在Touch Move Thu Jan 13 11:20:05   .local DragDrop [536]:

     

CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.200   DragDrop [536:207] x:0 y:1079885824

3 个答案:

答案 0 :(得分:13)

您通常不会直接在触摸检测方法中绘图。 通常,您只需在那里存储新的点/线,并在drawRect:中绘制所有点/线。假设您有一个UIView的自定义子类,它具有类型为paths的实例变量NSMutableArray和类型为currentPath的属性UIBezierPath。然后,您可以大致像这样实现触摸检测和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];
  }
}

请注意,这简化了很多。如果你绘制很多行,性能将受到影响,最终,你会想要将图形缓存在位图图像中,但这应该让你开始。

答案 1 :(得分:1)

使用我的这个答案,画一条线(自由的手)。

Not able to include undo/redo with smooth free hand drawing

希望这会有所帮助

答案 2 :(得分:0)

调用AddLineToPoint后需要调用CGContextStrokePath。 确保首先定义笔划路径颜色。

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