Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing performance UIGraphicsBeginImageContextWithOptions scale factor with Swift in Xcode for iOS app

I have a method for drawing, but drawing performance is greatly affected when adjusting the scale factor for UIGraphicsBeginImageContextWithOptions.

When the scale is 1.0, everything works super fast, however, when the scale factor is either 0.0, 2.0 or 3.0 for retina displays, the performance is terrible with lots of lagging while drawing.

What can be modified to improve performance when using scale factor of 0.0, 2.0 or 3.0 for retina devices?

Draws slow, lagging:

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0.0)
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 2.0)
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 3.0)

Draws fast, no lagging:

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 1.0)
like image 249
user4806509 Avatar asked Sep 25 '15 15:09

user4806509


1 Answers

I'm not sure what kind of drawing you are performing, as the advice would vary depending on the application. For example, if you're drawing Text, then there are numerous settings to be configured on the current context like context?.setShouldSmoothFonts, setShouldSubpixelQuantizeFonts or setShouldSubpixelPositionFonts.

Apple by default, sets the quality of drawn images to be very high, and hence you may need to optimise performance by tweaking parameters of the current Core Graphics context, as shown below.

  1. You can try (before drawing) setting the CGInterpolationQuality of the current CGContext. There is a significant rendering speed improvement for .none or .low compared to .medium and .high, but this has to be balanced with image quality. Try as follows:

    UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0.0)
    let context = UIGraphicsGetCurrentContext()
    context?.interpolationQuality = .medium //Change this value as per your needs
    //Insert drawing code here.
    
  2. Consider using Patterns to speed up drawing code. e.g UIColor(patternImage: image).

  3. Tweak context parameters such as context?.setMiterLimit(-10) and context?.setShouldAntialias(false).

Note that you can try tweaking these context parameters using the scale factor of 1.0 as well as 0.0 in the UIGraphicsBeginImageContextWithOptions depending on the use case. To provide even faster rendering, with a lower image quality a parameter of 1.0 would make sense, whereas for a better image quality the scale factor can be set to 0.0.

like image 144
Pranav Kasetti Avatar answered Oct 05 '22 07:10

Pranav Kasetti