如何在用户触摸的位置画线?

时间:2012-10-28 15:30:49

标签: objective-c xcode

我正在尝试在一个对象和用户触摸的位置之间绘制一条线。我已经尝试了子类化,每次用户触摸屏幕时我都无法获得“ - (void)drawrect”来更新自己。我删除了那些文件,并尝试将代码放入“ - (void)touchesbegan”中,但它不起作用:

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

    UITouch *touch = [touches anyObject];
    CGPoint locationOfTouch = [touch locationInView:nil];
    // You can now use locationOfTouch.x and locationOfTouch.y as the user's coordinates



Int xpos = (int)(starShip.center.x);
int ypos = (int)(starShip.center.y);

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
       CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), starShip.center.x, starShip.center.y);
    //draws a line to the point where the user has touched the screen
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), locationOfTouch.x, locationOfTouch.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
}

1 个答案:

答案 0 :(得分:0)

仅在需要时才会调用

drawRect:。它会在第一次显示视图时自动调用,并且每次调整视图大小时都会自动调用。如果您希望在触摸后调用它,则必须调用[self setNeedsDisplay];

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setNeedsDisplay];
}

这将确保调用drawRect:方法。你没有直接调用drawRect:,因为你在一帧中多次调用它,视图会重复多次重绘。相反,您将其标记为需要使用setNeedsDisplay进行重绘。这种方式drawRect:只会被调用一次,无论您多久调用一次setNeedsDisplay