如何通过 Objective-C 中的触摸事件移动在 CGContext 中绘制的线?

How to move line drawn in CGContext by touch event in Objective-C?

我使用以下代码绘制线条,效果很好,但是如何通过触摸事件在上下文中移动绘制的线条?

- (void) drawLineFrom:(CGPoint)from to:(CGPoint)to width:(CGFloat)width
    {
        UIGraphicsBeginImageContext(self.frame.size);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(ctx, 1.0f, -1.0f);
        CGContextTranslateCTM(ctx, 0.0f, -self.frame.size.height);
        if (drawImage != nil) {
            CGRect rect = CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height);
            CGContextDrawImage(ctx, rect, drawImage.CGImage);
        }
        CGContextSetLineCap(ctx, kCGLineCapRound);
        CGContextSetLineWidth(ctx, width);
        CGContextSetStrokeColorWithColor(ctx, self.drawColor.CGColor);
        CGContextMoveToPoint(ctx, from.x, from.y);
        CGContextAddLineToPoint(ctx, to.x, to.y);
        CGContextStrokePath(ctx);
        CGContextFlush(ctx);
        drawImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        drawLayer.contents = (id)drawImage.CGImage;
    }

如何从CGContext获取画线的引用?提前致谢。

UIGraphicsBeginImageContext() 开始一个图像上下文——一个像素网格。

drawImage = UIGraphicsGetImageFromCurrentImageContext();drawLayer.contents = (id)drawImage.CGImage; 将层的内容设置为该像素网格的捕获形式。

中间 UIGraphicsEndImageContext() 结束了您拥有的上下文。上下文不再存在。

所以从字面上回答你的问题:

  • 您不能要求图像上下文告诉您绘制到它的是什么,并期望它比绘制的单个像素具有更高层次的洞察力;
  • 你不能问你画的上下文,因为它已经不存在了。

正常的做法是创建一个 UIView,其中包含一系列描述您想要的关于该行的任何属性。实施 -drawRect: 并在其中根据属性画线。当您要更新行时,请更新属性。确保 属性 设置器调用 setNeedsDisplay.

在 UIKit 中,交互的东西应该是 UIView 的子类。系统请求时绘制视图。正常模式是拉,而不是推。