Creating a Core Graphics Context

suggest change

Core Graphics context

A Core Graphics context is a canvas you can draw on. You can set properties such as 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 = CGSizeMake(256, 256);

UIGraphicsBeginImageContextWithOptions(size, NO, 0);

CGContextRef context = UIGraphicsGetCurrentContext();

// drawing code here

UIGraphicsEndImageContext();

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

  1. A CGSize for the context, in points.
  2. A Boolean. true makes the context opaque.
  3. The scale as a CGFloat: 1 for non-Retina, 2 for Retina, and 3 for Super Retina. Pass 0 to use the device scale.

Feedback about page:

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



Table Of Contents