【问题标题】:How to move line drawn in CGContext by touch event in Objective-C?如何通过Objective-C中的触摸事件移动CGContext中绘制的线条?
【发布时间】:2016-12-20 14:56:01
【问题描述】:

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

- (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 获取画线的参考?提前致谢。

【问题讨论】:

    标签: objective-c cocoa-touch core-graphics core-animation


    【解决方案1】:

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

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

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

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

    • 您不能要求图像上下文告诉您绘制到它的内容并期望它具有比绘制的单个像素更高级别的洞察力;
    • 您无法询问您绘制的任何内容的上下文,因为它不再存在。

    通常的做法是创建一个UIView,其中包含一堆属性,这些属性描述了您想要的关于该行的任何内容。实现-drawRect: 并在其中根据属性画线。当您要更新线路时,请更新属性。确保属性设置器调用setNeedsDisplay

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2014-02-15
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多