Topics

#39: CGPath Basics πŸ“ˆ

Topics

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.

@IBDesignable
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)

    UIColor.lightGrayColor().setStroke()
    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)