Core Graphics Tutorial: Getting Started
In this Core Graphics tutorial, you’ll learn about using Core Graphics to design pixel-perfect views and how to use Xcode’s interactive storyboards. By Andrew Kharchyshyn.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Core Graphics Tutorial: Getting Started
35 mins
- Getting Into the Flo
- Getting Started
- Creating a Custom Drawing on Views
- Setting Auto Layout Constraints
- Drawing the Button
- Peeking Behind the Core Graphics Curtain
- Introducing @IBDesignable
- Drawing Into the Context
- Analyzing Points and Pixels
- Introducing @IBInspectable
- Adding a Second Button
- Adding Arcs with UIBezierPath
- Enjoying an Impromptu Math Lesson
- Returning to Arcs
- Outlining the Arc
- Making it All Work
- Where to Go From Here?
You just finished an app. It works fine, but the interface lacks style and grace. You could give it a makeover by drawing several sizes of custom control images in Photoshop and hope Apple doesn’t release a @4x retina screen. That plan, however, lacks strategy and sounds time-consuming. Alternatively, you could use Core Graphics to create an image that scales crisply for any device size.
Core Graphics is Apple’s vector drawing framework. It’s a big, powerful application programming interface (API) with many tools to master and cool features like @IBDesignable
and @IBInspectable
.
But never fear! This three-part series takes a modern approach to Core Graphics. It starts slow and eases you in with fun, engaging exercises. By the end, you’ll be able to create stunning graphics for your apps.
So sit back and relax with your favorite beverage. It’s time to learn Core Graphics!
Getting Into the Flo
Imagine a doctor recommends you drink eight glasses of water a day. No problem, you think. But after a few days, you realize how easy it is to lose track. Did you down three glasses this afternoon or two? Did you have your water bottle at your desk yesterday or the day before?
In this tutorial, you’ll create an app to track your drinking habits. With it, every time you polish off a refreshing glass of H2O, you tap a counter button. As data accumulate, the app will create a graph displaying your weekly consumption.
This app will be named Flo, and here it is in its completed glory:
Getting Started
Download the project materials by clicking the Download Materials button at the top or bottom of this tutorial. Open the starter project in Xcode.
Build and run. You’ll see the following:
You now have a starter project with a storyboard and a view controller, the rest is for you to build!
Creating a Custom Drawing on Views
There are three steps for custom drawings:
- Create a
UIView
subclass. - Override
draw(_:)
and add some Core Graphics drawing code. - Take pride in your work. :]
You’ll try this out by designing a custom plus button. It will look like this:
Create a new file by selecting File ▸ New ▸ File…. Then choose iOS ▸ Source ▸ Cocoa Touch Class. Click Next.
On this screen, name the new class PushButton, make it a subclass of UIButton, and ensure the language is Swift. Click Next and then Create.
UIButton
is a subclass of UIView
, all of the methods in UIView
, such as draw(_:)
, will be available in UIButton
.In Main.storyboard, drag a UIButton
into the view controller’s view, and select the button in Document Outline.
In the Identity inspector, change the class to use your own PushButton.
Setting Auto Layout Constraints
Next you’ll set up the Auto Layout constraints:
- With the button selected, Control-drag from the center of the button slightly left while staying within the button. Choose Width from the pop-up menu.
- With the button selected, Control-drag from the center of the button slightly up while staying within the button. Choose Height from the pop-up menu.
- Control-drag left from inside the button to outside the button. Choose Center Vertically in Container.
- Control-drag up from inside the button to outside the button. Choose Center Horizontally in Container.
This creates the four required Auto Layout constraints. You can now see them in the Size inspector:
Click Edit on Align center Y to, and set its constant to 100. This change shifts the vertical position of the button from the center to 100 points below the center. Similarly, change Width and Height constants to 100. The final constraints should look like this:
In the Attributes inspector, remove the default title Button.
You could build and run the app right now, but if you did, you’d see a blank screen. Time to fix that!
Drawing the Button
Recall the button you’re trying to make is circular:
To draw a shape in Core Graphics, you define a path that tells Core Graphics the line to trace — such as two straight lines for the plus — or the line to fill — such as the circle. If you’re familiar with Illustrator or the vector shapes in Photoshop, then you’ll understand paths.
There are three fundamentals to know about paths:
- A path can be stroked and filled.
- A stroke outlines the path in the current stroke color.
- A fill will fill a closed path with the current fill color.
An easy way to create a Core Graphics path is a handy class called UIBezierPath
. This class lets you develop paths with a user-friendly API. The paths can be based on lines, curves, rectangles or a series of connected points.
Start by using UIBezierPath
to create a path and then filling it with a green color. Open PushButton.swift and add this method:
override func draw(_ rect: CGRect) {
let path = UIBezierPath(ovalIn: rect)
UIColor.green.setFill()
path.fill()
}
You created an oval-shaped UIBezierPath
the size of the rectangle passed to it. In this case, it’ll be the size of the 100×100 button you defined in the storyboard, so the oval will be a circle.
Since paths don’t draw anything, you can define them without an available drawing context. To draw the path, you set a fill color on the current context and then fill the path. You’ll learn more about this later.
Build and run. You’ll see the green circle.
So far, you’ve discovered how to make custom-shaped views. You did this by creating a UIButton
, overriding draw(_:)
and adding UIButton
to your storyboard.