【问题标题】:Drawing CGContext Line with TouchesMoved in iOS在 iOS 中使用 TouchesMoved 绘制 CGContext 线
【发布时间】:2017-02-24 23:17:31
【问题描述】:

我正在使用 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();
    }
}

【问题讨论】:

标签: ios objective-c core-graphics


【解决方案1】:

嗯,从球的中心到触球位置的 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)

所以,把你的线画到那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    相关资源
    最近更新 更多