在iPhone上从静止点到移动点画一条线

发布于 2024-09-28 13:19:11 字数 66 浏览 0 评论 0原文

如何在一个点(一个 UIView 的中心)到一个移动点(触摸位置)之间绘制一条线,并且该线随着触摸移动而移动第二个点。

How can I draw a line between one point (the center of one UIView) to a point that moves (touch location), and the line moves the 2nd point as the touch moves.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

信仰 2024-10-05 13:19:11

在你的自定义视图中:

  • 在touchesMoved:withEvent中将当前点存储到一个变量中,并调用[self setNeedsDisplay]以便视图重绘,
  • drawRect:中实现线条绘制,使用核心图形绘制一条线

假设您将触摸点存储到属性self.touchedPoint中,那么绘制可能如下所示:

@property (nonatomic, assign) CGPoint touchedPoint;

- (void)drawRect:(CGRect)rect
{
 CGContextRef context = UIGraphicsGetCurrentContext();       
 CGContextSaveGState(context);

 CGContextTranslateCTM(context, 0.0, rect.size.height);
 CGContextScaleCTM(context, 1.0, -1.0);

 CGContextSetShouldAntialias(context, YES);
 CGContextSetLineWidth(context, 1.0f);
 CGContextSetRGBStrokeColor(context, 0.7, 0.7, 0.7, 1.0);

 CGContextMoveToPoint(context, rect.size.width/2, rect.size.height/2);
 CGContextAddLineToPoint(context, self.touchedPoint.x, self.touchedPoint.y);
 CGContextDrawPath(context, kCGPathStroke); 

 CGContextRestoreGState(context);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.touchedPoint = [[touches anyObject] locationInView:self];
    [self setNeedsDisplay];
}

In your custom view:

  • in touchesMoved:withEvent store current point into a variable, and call [self setNeedsDisplay] so that the view would redraw
  • implement drawing of a line in drawRect:, use core graphics to draw a line

Let's say you store the touched point into property self.touchedPoint, then drawing might look like this:

@property (nonatomic, assign) CGPoint touchedPoint;

- (void)drawRect:(CGRect)rect
{
 CGContextRef context = UIGraphicsGetCurrentContext();       
 CGContextSaveGState(context);

 CGContextTranslateCTM(context, 0.0, rect.size.height);
 CGContextScaleCTM(context, 1.0, -1.0);

 CGContextSetShouldAntialias(context, YES);
 CGContextSetLineWidth(context, 1.0f);
 CGContextSetRGBStrokeColor(context, 0.7, 0.7, 0.7, 1.0);

 CGContextMoveToPoint(context, rect.size.width/2, rect.size.height/2);
 CGContextAddLineToPoint(context, self.touchedPoint.x, self.touchedPoint.y);
 CGContextDrawPath(context, kCGPathStroke); 

 CGContextRestoreGState(context);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.touchedPoint = [[touches anyObject] locationInView:self];
    [self setNeedsDisplay];
}
迷离° 2024-10-05 13:19:11

我对米哈尔的回答投了赞成票。但我还建议查看 Touches 示例项目。让它运行起来很容易 - 如果您仍在整理项目,这可能会有所帮助。

I voted Michal's answer up. But I would also suggest looking at the Touches sample project. It is easy to get it running - which may be helpful if you are still just putting together your project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文