Draw Paths in UIViews
In a previous tip, I drew rectangles and circles in a UIView. This time, let’s add lines and curves using paths to draw some toast.
Download the playground I set up for you. I set up my code to do all the drawing in the
drawLines method. Go to the closure.
I set up a drawing frame size to be the entire frame size of the view. I also added a few points in the array to draw the toast.
let drawPoints:[CGPoint] = [CGPoint(x: 300, y:300),CGPoint(x: 300, y: 500),CGPoint(x: 500, y: 500),CGPoint(x: 500, y: 300)]
let imagerenderer = UIGraphicsImageRenderer(size: frame.size)
Before you draw, you should set a few properties. Start with color. For the fill color of our toast, I’ll add brown using the
setFill method of
Then I’ll add purple for a contrasting stroke color using the
setStroke method of
You can also set the shape of the line cap. You do that in the
cgContext of the closure’s
I’ll do the same with the line join giving a slightly curved look to the joints at lines.
The foundation of the drawing is a path. You make a path and then draw that path. You start a new path with a
For the first point in our path, you move to a point. I’ll move to the first point in the array
To add a line you use the
addLine method. This method specifies the point you are going to, using the current point as a start.
With one line, we can try out our line. Before we do, draw it first using the
drawPath has a paramater
using, which has several options for how to draw the path. I can fill the path, leave a stroke or both. I’ll start with the stroke.
Run this, and You’ll see a line in the live view.
I’ll add another line.
Once I have two lines I can startusing fills in
drawpath. I’ll change to
I’ll run again and get a triangle.
The path assumes the endpoint of the path is the beginning point for the fill. This triangle is still open though. To see the stroke better, I’ll make the line a bigger width. You use the
setLineWidth method on
cgContext, which I’ll get from the context in the closure. So add this, just above the
.fillStroke to draw a line and a stroke both.
Run again, and you’ll see the fill connects even if the shape is not closed.
I’ll add one more line:
Run this. We get a three lines around a filled square.
Next, I’ll add a quad curve, one of several curves. This one has a single control point found in the center of the point. I’m going to at first set it to the midpoint of the curve to make this a line.
context.cgContext.addQuadCurve(to: drawPoints, control: CGPoint(x: 400, y: 300))
Run this and you get a square.
The control point on a quad curve curves according to the position of the control point. I’ll move the control point up 100 points.
context.cgContext.addQuadCurve(to: drawPoints, control: CGPoint(x: 400, y: 200))
And you have a piece of toast. I’ve used Playgrounds here to allow for interactive design, but any UIView can use this technique. Explore lines and quad curves for a variety of applications.