Drawing 2D Graphics in iOS Swift
Posted By : Varun Wadhwa | 10-Apr-2017
In this I'll explain how to draw 2D graphics using Core Graphics in iOS Swift. We will use Quardz 2D API.
Quardz 2D is low level light-weight 2D rendring and drawing engine.It is based on coordinate system (0,0) represent the device top left corner. In iOS CGPoint (a structure) is used to specify a point. similarly rectangle can be defined by CGRect structure.
Graphics Context : View has a graphic context which is responsible for drawing requests, so to draw on device screen we need graphics context of view. so to graphics context we've to call UIGraphicsGetCurrentContext() which return CGContextRef.
let contextRef = UIGraphicsGetCurrentContext()
Drawing Paths : For drawing we've to subclass a UIView class.
import UIKit
class Draw2D: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setLineWidth(2.0)
context?.setStrokeColor(UIColor.blue.cgColor)
context?.move(to: CGPoint(x:100, y: 100))
context?.addLine(to: CGPoint(x: 150, y: 150))
context?.addLine(to: CGPoint(x: 100, y: 200))
context?.addLine(to: CGPoint(x: 50, y: 150))
context?.addLine(to: CGPoint(x: 100, y: 100))
context?.strokePath()
}
}
Filling Paths with Color : For filling the paths we'll use cgColor property of UIColor class.
context?.setFillColor(UIColor.red.cgColor) context?.fillPath()
Drawing Qurardatic Beizer curve : Instead of addLine function we'll add addQuadCurve function to draw curves.
context?.addQuadCurve(to: CGPoint(x: 300, y: 200), control: CGPoint(x: 150, y: 10))
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Varun Wadhwa
Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.