Creating a Core Graphics Context

suggest change

Core Graphics context

A Core Graphics context is a canvas which we can draw in it and set some properties like the line thickness.

Making a context

To make a context, we use the UIGraphicsBeginImageContextWithOptions() C function. Then, when we are done with drawing, we just call UIGraphicsEndImageContext() to end the context:

Swift

let size = CGSize(width: 256, height: 256)

UIGraphicsBeginImageContextWithOptions(size, false, 0)

let context = UIGraphicsGetCurrentContext()

// drawing code here

UIGraphicsEndImageContext()

Objective-C

CGSize size = [CGSize width:256 height:256];

UIGraphicsBeginImageContextWithOptions(size, NO, 0);

CGContext *context = UIGraphicsGetCurrentContext();

// drawing code here

UIGraphicsEndImageContext();

In the code above, we passed 3 parameters to the UIGraphicsBeginImageContextWithOptions() function:

  1. A CGSize object which stores the whole size of the context (the canvas)
  2. A boolean value which if it is true, the context will be opaque
  3. An integer value which sets the scale (1 for non-retina, 2 for retina and 3 for retina HD screens). If set to 0, the system automatically handles the scale based on the target device.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Core Graphics:
* Creating a Core Graphics Context

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
100 Core Graphics
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable