Joe Blow Joe Blow - 6 months ago 172
iOS Question

Draw dotted (not dashed!) line

It's pretty easy to draw a dashed line with UIKit. For example:

CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];

enter image description here

But is there any way way to draw a genuine "dotted line"?

enter image description here

Any ideas?

BTW, if you need a dashed line: To save some typing, here's a handy class for a dashed line...

@interface UIDashedLine : UIView

// Extremely easy way to draw a dashed line:
// Simply place an empty UIView in the storyboard, where you want the line.
// Change the class of the UIView, to UIDashedLine.
// At runtime it will draw a perfect dashed line,
// wherever you placed the view in storyboard.

@implementation UIDashedLine

CGFloat thickness = 4.0;

CGContextRef cx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(cx, thickness);
CGContextSetStrokeColorWithColor(cx, [UIColor blackColor].CGColor);

CGFloat ra[] = {4,2};
CGContextSetLineDash(cx, 0.0, ra, 2); // nb "2" == ra count

CGContextMoveToPoint(cx, 0,thickness*0.5));
CGContextAddLineToPoint(cx, self.bounds.size.width, thickness*0.5);



Set the line cap style to round and set the “on” length to zero.

Swift playground example:

import UIKit
import XCPlayground

let path = UIBezierPath()
path.moveToPoint(CGPointMake(10, 10))
path.addLineToPoint(CGPointMake(290, 10))
path.lineWidth = 8

let dashes: [CGFloat] = [path.lineWidth * 0, path.lineWidth * 2]
path.setLineDash(dashes, count: dashes.count, phase: 0)
path.lineCapStyle = CGLineCap.Round

UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 20), false, 2)

XCPlaygroundPage.currentPage.captureValue(UIGraphicsGetImageFromCurrentImageContext(), withIdentifier: "image")



For objective-C, using the same example class as in the question, simply add

CGContextSetLineCap(cx, kCGLineCapRound);

before the call to CGContextStrokePath, and change the ra array values to match my Swift code.