23

I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
[shapeLayer setLineWidth:2.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:5],
  nil]];

Now if I want to just draw a dashed line from point X to point B, how should I modify this code?

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
adit
  • 32,574
  • 72
  • 229
  • 373

8 Answers8

61

Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:

CGContextBeginPath(context);
CGContextMoveToPoint(context, 10.5f, 10.5f);
CGContextAddLineToPoint(context, 20.5f, 20.5f);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);

For drawing dashed line, You need to use CAShapeLayer

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:self.center];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[shapeLayer setLineWidth:3.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
 [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
  [NSNumber numberWithInt:5],nil]];

// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 10, 10);
CGPathAddLineToPoint(path, NULL, 100,100);

[shapeLayer setPath:path];
CGPathRelease(path);

[[self layer] addSublayer:shapeLayer];
Bryan Bryce
  • 1,310
  • 1
  • 16
  • 29
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
12

Try this code, it works for me,

Swift 3.0

extension UIView {
    func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {

        backgroundColor = .clear

        let shapeLayer = CAShapeLayer()
        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = bounds
        shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path = CGMutablePath()
        path.move(to: CGPoint.zero)
        path.addLine(to: CGPoint(x: frame.width, y: 0))
        shapeLayer.path = path

        layer.addSublayer(shapeLayer)
    }
}
Khawar
  • 9,151
  • 9
  • 46
  • 67
Patel Jigar
  • 2,141
  • 1
  • 23
  • 30
5

See:

https://developer.apple.com/library/mac/documentation/graphicsimaging/Reference/CGContext/Reference/reference.html#//apple_ref/c/func/CGContextSetLineDash

CGFloat dashLengths[] = { 10, 5 };
CGContextSetLineDash(context, 0, dashLengths, 2);
wpearse
  • 2,422
  • 2
  • 29
  • 30
2

Swift 2.2

dropping this in here to save others time..

extension UIView {
    func addDashedLine(color: UIColor = UIColor.lightGrayColor()) {
        layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
        self.backgroundColor = UIColor.clearColor()
        let cgColor = color.CGColor

        let shapeLayer: CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = cgColor
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path: CGMutablePathRef = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, 0, 0)
        CGPathAddLineToPoint(path, nil, self.frame.width, 0)
        shapeLayer.path = path

        self.layer.addSublayer(shapeLayer)
    }
}
Alexandre G
  • 1,655
  • 20
  • 30
1

Swift, more compact:

func addDashedLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(start)
    linePath.addLineToPoint(end)
    line.path = linePath.CGPath
    line.strokeColor = UIColor.redColor().CGColor
    line.lineWidth = 1
    line.lineJoin = kCALineJoinRound
    line.lineDashPattern = [4, 4]
    self.layer.addSublayer(line)
}
Wujo
  • 1,845
  • 2
  • 25
  • 33
1

Below is the code snippet to draw a Dashed line in UIView (Xamarin iOS)

Note: separatorView is my UIView which i need to show as Dashed

 public void ShowDottedLine()
 {
      var dashedLayer = new CAShapeLayer();
      var frameSize = separatorView.Frame.Size;
      var shapeRect = new CGRect(0, 0, frameSize.Width, frameSize.Height);
      dashedLayer.Bounds = shapeRect;
      dashedLayer.Position = new CGPoint(frameSize.Width / 2, frameSize.Height / 2);
      dashedLayer.FillColor = UIColor.Clear.CGColor;
      dashedLayer.StrokeColor = ColorUtils.ColorWithHex(ColorConstants.DarkBlue).CGColor;
      dashedLayer.LineWidth = 2;
      dashedLayer.LineJoin = CAShapeLayer.JoinRound;
      NSNumber[] patternArray = {5,5};
      dashedLayer.LineDashPattern = Array;
      var path = new CGPath();
      path.MoveToPoint(CGPoint.Empty);
      path.AddLineToPoint(new CGPoint(frameSize.Width, 0));
      dashedLayer.Path = path;
      separatorView.Layer.AddSublayer(dashedLayer);
 }
Prashant
  • 244
  • 2
  • 16
0

Got it working in Objective C with the simplified code as below

   //Dashed line for road
    CAShapeLayer *dashedLine = [CAShapeLayer layer];
    [dashedLine setFrame:CGRectMake(0, 342, 100 , 100)];

    // Setup the path
    CGMutablePathRef thePath = CGPathCreateMutable();
    CGPathMoveToPoint(thePath, NULL, 0, 10);
    CGPathAddLineToPoint(thePath, NULL, screenSize.width,10);
    dashedLine.path = thePath;
    CGPathRelease(thePath);

    [dashedLine setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithFloat:15], nil]];
    dashedLine.lineWidth = 1.0f;
    dashedLine.strokeColor =  [[UIColor redcolor] CGColor]];

    [self.view.layer addSublayer:dashedLine];
Naishta
  • 11,885
  • 4
  • 72
  • 54
0
CAShapeLayer *shaplayer = [CAShapeLayer layer];
    shaplayer.frame = CGRectMake(100, 100, 100, 100);
    [self.view.layer addSublayer:shaplayer];
    UIBezierPath *uipath = [UIBezierPath bezierPath];
    [uipath moveToPoint:CGPointMake(50, 200)];
    [uipath addLineToPoint:CGPointMake(250, 200)];
    shaplayer.path = uipath.CGPath;
    shaplayer.strokeColor = [UIColor redColor].CGColor;
    shaplayer.lineDashPattern = @[@4];
sfm.json
  • 17
  • 5
  • 1
    Thank you for this code snippet, which may provide some immediate help. A proper explanation would [greatly improve](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – basvk Jul 04 '17 at 11:40