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

339 Views Asked by At

I used following code to draw line which works fine but How to move that drawn line within context by touch event?

- (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;
    }

How to get reference of drawn line from CGContext ? thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

UIGraphicsBeginImageContext() begins an image context — one that is a grid of pixels.

drawImage = UIGraphicsGetImageFromCurrentImageContext(); and drawLayer.contents = (id)drawImage.CGImage; set the contents of a layer to a captured form of that grid of pixels.

The intermediate UIGraphicsEndImageContext() ends the context you had. The context no longer exists.

So to answer you question literally:

  • you can't ask an image context to tell you what was drawn to it and expect it to have any higher-level insight than the individual pixels that were plotted;
  • you can't ask the context you drew to anything, because it no longer exists.

The normal thing to do would be to create a UIView with a bunch of properties that describe whatever you want about the line. Implement -drawRect: and in there draw the line based on the properties. When you want to update the line, update the properties. Ensure the property setters make a call to setNeedsDisplay.

In UIKit things that are interactive should be subclasses of UIView. Views draw when requested to by the system. The normal pattern is pull, not push.