iosiphoneswiftcore-graphicsline

How to make a dashed line in swift?


I want to know how to make a dashed line in swift like this: - - - - - - - - instead of a regular straight line like this: ----------------, I know that i can make multiple lines but that will require so much unnecessary code if i can just write it in 1 line. Btw it has to be in CoreGraphics.


Solution

  • You create Dashed Lines the same way as Objective-C, except that you'll use Swift.

    Here is how you do it using UIBezierPath:

    let  path = UIBezierPath()
    
    let  p0 = CGPoint(x: self.bounds.minX, y: self.bounds.midY)
    path.move(to: p0)
    
    let  p1 = CGPoint(x: self.bounds.maxX, y: self.bounds.midY)
    path.addLine(to: p1)
    
    let  dashes: [ CGFloat ] = [ 16.0, 32.0 ]
    path.setLineDash(dashes, count: dashes.count, phase: 0.0)
    
    path.lineWidth = 8.0
    path.lineCapStyle = .butt
    UIColor.magenta.set()
    path.stroke()
    

    Here is how to draw Dotted Lines using UIBezierPath:

    let  path = UIBezierPath()
    
    let  p0 = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMidY(self.bounds))
    path.moveToPoint(p0)
    
    let  p1 = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMidY(self.bounds))
    path.addLineToPoint(p1)
    
    let  dashes: [ CGFloat ] = [ 0.0, 16.0 ]
    path.setLineDash(dashes, count: dashes.count, phase: 0.0)
    path.lineWidth = 8.0
    path.lineCapStyle = .Round
    UIColor.magentaColor().set()
    path.stroke()
    

    Here is how to draw Dashed Lines Using CGContext:

    let  context: CGContext = UIGraphicsGetCurrentContext()!
    
    let  p0 = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMidY(self.bounds))
    CGContextMoveToPoint(context, p0.x, p0.y)
    
    let  p1 = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMidY(self.bounds))
    CGContextAddLineToPoint(context, p1.x, p1.y)
    
    let  dashes: [ CGFloat ] = [ 16.0, 32.0 ]
    CGContextSetLineDash(context, 0.0, dashes, dashes.count)
    
    CGContextSetLineWidth(context, 8.0)
    CGContextSetLineCap(context, .Butt)
    UIColor.blueColor().set()
    CGContextStrokePath(context)