在 iOS 中使用 TouchesMoved 绘制 CGContext 行
Drawing CGContext Line with TouchesMoved in iOS
我正在 Objective-C 中为 iOS 创建一个球滑动游戏,您可以在其中滑动屏幕,球就会移动。我已将其设置为使球沿与您滑动的方向相反的方向移动。例如,如果我向下滑动并松开,球就会向上移动。
我使用 CGContext 创建了一条线来显示球的移动方向。该线从球的中心 (ball.center.x, ball.center.y) 开始到您用手指滑动的点 (movePoint)。我试图拥有它,所以当我滑动屏幕时,它不会在 movePoint 上画一条线,而是在相反的方向上画一条线。例如,如果我在屏幕上向下滑动,就会向上画一条线。
我试过摆弄坐标系,但我似乎无法让它正确指向我滑动位置的相反方向。有什么特别的方法可以解决这个问题吗?
谢谢。
这是我的 touchesMoved 函数:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
movePoint = [touch locationInView:self.view];
if (CGRectContainsPoint([ball frame], firstPoint)) {
_contextImage.hidden = NO;
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextMoveToPoint(context, ball.center.x, ball.center.y);
CGContextAddLineToPoint(context, movePoint.x, movePoint.y);
CGContextStrokePath(context);
self.contextImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
那么,从球的中心到触球位置的 delta-X 将为 movePoint.x - ball.center.x
。另一种说法是触摸位置的 X 坐标是 ball.center.x + (movePoint.x - ball.center.x)
,对吗?好吧,相反方向的点是通过减法而不是加法计算的(或者,换句话说,通过取反 delta-X):ball.center.x - (movePoint.x - ball.center.x)
.
Y 位置也是如此:ball.center.y - (movePoint.y - ball.center.y)
。
所以,画一条线到那里。
我正在 Objective-C 中为 iOS 创建一个球滑动游戏,您可以在其中滑动屏幕,球就会移动。我已将其设置为使球沿与您滑动的方向相反的方向移动。例如,如果我向下滑动并松开,球就会向上移动。
我使用 CGContext 创建了一条线来显示球的移动方向。该线从球的中心 (ball.center.x, ball.center.y) 开始到您用手指滑动的点 (movePoint)。我试图拥有它,所以当我滑动屏幕时,它不会在 movePoint 上画一条线,而是在相反的方向上画一条线。例如,如果我在屏幕上向下滑动,就会向上画一条线。
我试过摆弄坐标系,但我似乎无法让它正确指向我滑动位置的相反方向。有什么特别的方法可以解决这个问题吗?
谢谢。
这是我的 touchesMoved 函数:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
movePoint = [touch locationInView:self.view];
if (CGRectContainsPoint([ball frame], firstPoint)) {
_contextImage.hidden = NO;
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextMoveToPoint(context, ball.center.x, ball.center.y);
CGContextAddLineToPoint(context, movePoint.x, movePoint.y);
CGContextStrokePath(context);
self.contextImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
那么,从球的中心到触球位置的 delta-X 将为 movePoint.x - ball.center.x
。另一种说法是触摸位置的 X 坐标是 ball.center.x + (movePoint.x - ball.center.x)
,对吗?好吧,相反方向的点是通过减法而不是加法计算的(或者,换句话说,通过取反 delta-X):ball.center.x - (movePoint.x - ball.center.x)
.
Y 位置也是如此:ball.center.y - (movePoint.y - ball.center.y)
。
所以,画一条线到那里。