1

我试图在一个对象和用户触摸的位置之间画一条线。我已经尝试过子类化,但每次用户触摸屏幕时,我都无法让“-(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());
}
4

1 回答 1

0

drawRect:仅在需要时调用。它在第一次显示视图和每次调整视图大小时自动调用。如果你想在触摸后调用它,你必须调用[self setNeedsDisplay];

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

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

于 2012-10-28T15:36:53.547 回答