views:

238

answers:

2

Hi,

I have an UIView which I want to give a gradient background and I'm wondering how to implement that as efficient as possible.

I am considering three options:

  1. Create an UIImageView as subview and give it an image of the gradient to display.

  2. Draw the gradient image in drawRect: of the original UIView.

  3. Draw the gradient in drawRect:, but this time use CoreGraphics to 'create it from scratch'.

Which of these three would be the fastest/least memory intensive? (The fastest to run, not to write.)

Thanks!

+1  A: 
  • Creating a UIImageView as a subview of the main view would be the quickest way to get what you want.
  • Drawing the image onto the view's context would be the more memory intensive option.
  • Drawing the gradient in code using Core Graphics would be the more efficient way.

Things to keep in mind:

You have little-to-no control over when how often drawRect executes, so you don't want to be doing things like memory allocation within that method.

drawRect could be called more than once in the same run loop, so it's not a good idea to create autoreleased objects during that method either, because they may stack up and consume more memory than necessary.

Jasarien
Thank you very much!
Jongsma
Creating an image and then drawing that inside drawRect: will be more memory intensive, but quicker than drawing a gradient each time. If the app is CPU-bound, use a cached image; if the app memory-bound, draw the gradient directly.
rpetrich
A: 

If it is convenient to render the gradient into a UIImage - You may want to consider something like.

UIImage *gradientImage = GetGradientImage(); // your code self.view.backgroundColor = [UIColor colorWithPatternImage:gradientImage];

You'll want to balance the memory required for a big gradient with the time it takes to calculate and draw it repeatedly.

This works well in lots of places where you want to do minor customizations of backgrounds, or where you think you need a UIImageView, just to draw a background on another view.

Todd

Todd