Drawing a straight line iOS

北城余情 提交于 2020-01-23 04:17:28

问题


I am drawing a straight line using this code (on user touch obviously) and I need to display the straight line from the start point until where the user is holding the touch (not ended the touch) like a rubber band from the start point, following the finger wherever it moves. I might have overlooked something I need to modify to create the necessary effect. Any idea?

NOTE : I am inside a View Controller.

- (void) drawLine:(UIPanGestureRecognizer *)sender
{

    NSLog(@"Sender : %@", sender);
    CGPoint currentPoint;

    //CGAffineTransformMakeScale(lastScale, lastScale);
    if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateBegan ||                                       [(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateChanged)
    {
        currentPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView];

        previousPoint = currentPoint;
    }

    if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateChanged) 
    { 
        touchedPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView]; 
        [imgView setNeedsDisplay]; 
    }

    if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateEnded)
    {
        currentPoint = [(UIPanGestureRecognizer *)sender locationInView:imgView];
        imgView.image =  [self drawLineFromPoint:previousPoint toPoint:currentPoint   image:imgView.image];

        previousPoint = currentPoint;

    }

}

This is the [drawline frompoint: topoint:] method

UIGraphicsBeginImageContext(imgView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();       
CGContextSaveGState(context);

CGContextTranslateCTM(context, 0.0, imgView.frame.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, fromPoint.x, fromPoint.y);
CGContextAddLineToPoint(context, toPoint.x, toPoint.y);
CGContextDrawPath(context, kCGPathStroke); 

CGContextRestoreGState(context);

NSLog(@"frompoint.x : %f, frompoint.y : %f",fromPoint.x, fromPoint.y );
NSLog(@"topoint.x : %f, topoint.y : %f", toPoint.x, toPoint.y);

UIImage *ret = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

回答1:


DrawingApp This is a sample project I found which does what was desired.

Another approach is, as Lefteris suggested in the comment, inside UIView, override touches began, moved and ended. And use drawRect to draw the line. The line will drag to wherever your current touch is.



来源:https://stackoverflow.com/questions/12527482/drawing-a-straight-line-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!