How to draw images programmatically without Views or UIViews for your Tests

Would you like to gain some performance in your tests by drawing images without needing a UIViewController, UIView, or Views? This article shows how to draw a tiny square image using UIGraphicsImageRenderer without using an UIView/View and in any thread.

Because loading images locally using XCAssets can hit the performance of your tests by reading data from disk. It is better to use in-memory images so we don’t have to read from disk and not depend on name assets that might not be there when reading them.

Previously we would use UIGraphicsBeginImageContext like this:

But this will force you to manage Core Graphics contexts. i.e. you need to begin drawing the image using UIGraphicsBeginImageContext context and finish it using UIGraphicsEndImageContext. This creates a bitmap-based graphics where the image will be drawn. The size measured in points it receives represents the size of the image returned by the `UIGraphicsGetImageFromCurrentImageContext`.

While this is pretty straightforward, there are a couple of things that can be improved like:

  1. You must manage the created core graphics context in the same scope.

  2. You need to get the underlying UIImage’s data to get a png or jpeg version of the image.

Introducing UIGraphicsImageRenderer! with this new class, you can quickly draw your image specifying the size measured in points in a closure-based message call like this.

This way, you don’t have to manage your core graphics context for the image, and you can get access to an UIImage object, to its png or jpeg data version using image(actions:), jpegData(withCompressionQuality:actions:) and pngData(actions:) respectively.

UIGraphicsImage renderer is thread-safe. If you like custom drawing to your bit map, use the available APIs from the received CGContext class.

Note:

The renderer uses sensible defaults for the current device if you don't provide a format object. This might cause a problem when comparing data from an UIImageView Object and assertions to fail. For that reason, we need to provide the dimensions of the output image and a format object with a set scale (I’ve used 1) when creating a UIGraphicsImageRenderer.

References:
UIGraphicsImageRenderer

UIGraphicsBeginImageContextWithOptions function

Would you like to become an excellent iOS developer that thrives in any situation given? check out this website: Essential Developer

Previous
Previous

How to resolve the swiping right action when trying to navigate to a previous screen in iOS.

Next
Next

The Real Architecture inside MVC - The beginning