Core Graphics Tutorial: Lines, Rectangles, and Gradients

Learn how to use Core Graphics to draw lines, rectangles, and gradients — starting by beautifying a table view! By Ron Kliffer.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Drawing Lines

As a final bit of bling, you’ll add a splitter to each cell in the detail view. Open StarshipFieldCell.swift and add the following to the class:

override func draw(_ rect: CGRect) {
  guard let context = UIGraphicsGetCurrentContext() else {
    return
  }

  let y = bounds.maxY - 0.5
  let minX = bounds.minX
  let maxX = bounds.maxX

  context.setStrokeColor(UIColor.starwarsYellow.cgColor)
  context.setLineWidth(1.0)
  context.move(to: CGPoint(x: minX, y: y))
  context.addLine(to: CGPoint(x: maxX, y: y))
  context.strokePath()
}

Here, you use Core Graphics to stroke a line at the bottom of the cell’s bounds. Notice how the y-value used is half-a-point smaller than the bounds of the view to ensure the splitter is drawn fully inside the cell.

Now, you need to actually draw the line showing the splitter.

To draw a line between A and B, you first move to point A, which won’t cause Core Graphics to draw anything. You then add a line to point B, which adds the line from point A to point B into the context. You can then call strokePath() to stroke the line.

Build and run your app. Then, open the Y-wing detail view. Beautiful!

Finished starship detail

Where to Go From Here?

You can download the final project by clicking the Download Materials link at the top or bottom of this tutorial.

The download also includes two playgrounds. RedBluePlayground.playground contains the example set out in the context saving/restoring section, and ClippedBorderedView.playground demonstrates clipping a border unless it’s inset.

Additionally, DemoProject is a complete Xcode project, which strokes a rect over a one-point grid to help you understand the concept of anti-aliasing. It’s easy to understand now that you know the Core Graphics Swift API. :]

At this point, you should be familiar with some pretty cool and powerful techniques in Core Graphics: filling and stroking rectangles, drawing lines and gradients and clipping to paths. Not to mention your table view now looks pretty cool. Congratulations!

If this tutorial was a little hard to follow, or you want to make sure to cover your basics, check out the Beginning Core Graphics video series.

If you’re looking for something more advanced, take a look at the Intermediate Core Graphics course.

And if you don’t feel like you can commit to an entire course yet, try the Core Graphics Article Series, where you’ll learn how to draw an entire app, including graphs, from scratch with Core Graphics!

Plus, there are many more Core Graphics tutorials on raywenderlich.com.

If you have any questions or comments, please join the forum discussion below.