0

I am adding a simple drawing capability to an app and I want the user to be able to draw dashed lines. I have the drawing routine working just fine, adding a CAShapeLayer and setting the path.

However, when I try to draw dashed lines the dashes are apparent only when the user draws very FAST. If I draw slowly the line is solid as the dashes are bunched together.

Step 1. Start a new drawing layer. Some code obviously left out.

// CAShapeLayer
// Dashed pattern is arbitrary - I've tried a variety of values
[self.currentDrawLayer setLineDashPattern:[NSArray arrayWithObjects:
                                          [NSNumber numberWithInt:6],
                                          [NSNumber numberWithInt:12],
                                          nil]];

currentPenPath = [UIBezierPath bezierPath];    
[currentPenPath moveToPoint:currentPoint];

Step 2. Add points as the user draws and update the layer.

[currentPenPath addLineToPoint:currentPoint];
[currentPenPath moveToPoint:currentPoint];
[[self currentDrawLayer] setPath:currentPenPath.CGPath];

I want the user to be able to draw as slow or fast as they want and have consistent dashes while drawing. Do I need to smooth out all of the points or something first?

Is there a simple way to draw dashes as the user draws?

enter image description here

Any guidance is appreciated.

Christopher
  • 5,806
  • 7
  • 31
  • 41
  • It sounds like you need to post-process the path and remove points. – Lily Ballard Aug 28 '12 at 22:16
  • I've been thinking that. I gather I need to somehow create a new path which follows the same curve but with points evenly spaced. I'm not sure how to do that so I am researching. – Christopher Aug 28 '12 at 23:56

1 Answers1

0

I found a solution - and one that works while drawing too!

Some code...

else if (sender.state == UIGestureRecognizerStateChanged)
{
    CGFloat distance = sqrtf(powf((point.x - currentPenPoint.x), 2) + powf((point.y - currentPenPoint.y), 2));

    if (distance > 20) // TODO: define magic number after some testing
    {
        currentPenPoint = point;
        [self drawPenLine];
    }

    <snip>
}

I referenced the following post: How to draw Smooth straight line by using UIBezierPath?

Using Pythagoras I can find the distance between the previous point and if far enough I add the point and draw the line. This way the dashed lines are evenly spaced.

Community
  • 1
  • 1
Christopher
  • 5,806
  • 7
  • 31
  • 41
  • 1
    Skip the `sqrtf()` and just square your distance threshold. The behavior is the same but it'll be more efficient. – Lily Ballard Aug 29 '12 at 00:09