Want to offer native, in-app customer service to your users? Get going quickly with Zendeskโ€™s Mobile SDKs. Free with Zendesk.


#39: CGPath Basics ๐Ÿ“ˆ


CGPaths are how CoreGraphics describes the bezier paths it uses for drawing to the screen. They can go a long way to unlocking some of the power of CoreGraphics, so letโ€™s take a look:

We're going to create a custom disclosure indicator to use on our UITableView rows. Weโ€™ll create a CGPath, and add two lines to it that make up the arrow shape.

This kind of CoreGraphics code is largely imperative. You tell the system what to do in a bunch of steps.

class DisclosureIndicatorView : UIView {
  override func drawRect(rect: CGRect) {
    let path = CGPathCreateMutable()

    // move to top-left
    CGPathMoveToPoint(path, nil, bounds.origin.x, bounds.origin.y)

    // add line to middle-right
    CGPathAddLineToPoint(path, nil, bounds.size.width, CGRectGetMidY(bounds))

    // move to bottom-left
    CGPathMoveToPoint(path, nil, bounds.origin.x, bounds.size.height)

    // add another line to middle-right
    CGPathAddLineToPoint(path, nil, bounds.size.width, CGRectGetMidY(bounds))

    let context = UIGraphicsGetCurrentContext()
    CGContextAddPath(context, path)

    CGContextSetLineWidth(context, 2.0);

    CGContextDrawPath(context, kCGPathStroke)

We tell CoreGraphics to move to the top-left point in our view, then we ask the system to add line, then move again, and so on.

Finally we add the path to our context, and draw the path to the screen using a light gray color, and a 2-pixel wide line.

Pro Tip: Add @IBDesignable to your view so you can preview it in Interface Builder! (shown below)