Reputation: 6353
On iOS devices, in which occasions is it better to draw graphics using Core Graphics than using image files?
What are the advantages of doing so in terms of resources?
Upvotes: 25
Views: 3703
Reputation: 2286
I think, images are better for it's performance. But, when we want to develop something which will can be changed (eg. color change, shape change etc.), scaled or can be animated, then, we should go for core graphics.
Core graphics is amazing when we want to draw something with some mathematical logic and want to play with that! In schools, we all learn circle equation, line equation etc. in mathematics. Core graphics is the right tool to visualise our mathematical knowledge and build some more crazy things with that!
Core graphics is also very useful for simulation type applications.
Upvotes: 1
Reputation: 63667
Images vs Core Graphics is a blunt distinction. The methods to render offscreen/onscreen graphics are more complex to the point that you need to use Instruments to find out what is really happening. I tried to provide an overview here, but this answer could use some improving from more knowledgeable people.
Graphics are always rendered onscreen by the GPU. However, they can be generated by the GPU or the CPU, and happen in user code or in a separate process called “the render server”. Here is an overview:
CPU, user code:
drawRect()
. The result is usually cached.GPU, render server:
shouldRasterize
set to YES. This creates a cache of the layer and sublayers.GPU, render server, very slow:
setMasksToBounds
) and dynamic shadows (setShadow*
).UIViewGroupOpacity
). GPU, fast:
Note that caching is only useful if the cache is reused. If it is immediately discarded it hurts performance. For example, a cached animation where contents are simply stretched can be cached and reused, but a cached animation where contents change will have an awful performance.
Image files are generally faster.
imageNamed:
instead initWithData:
.Offscreen drawing requires more work, but lets you achieve more.
-[CALayer setShouldRasterize:YES]
and -[CALayer setRasterizationScale:]
.Stretchable images, whether read from image files, or generated by drawing, use less memory. Stretching is an unexpensive operation to the GPU.
Performance is only a problem if there isn't enough. Use whatever is faster to code unless pressed otherwise. The fastest program is the one that reaches the market first.
Some interesting reading:
Upvotes: 37
Reputation: 42554
In my experience it's always better to use images from a performance point of view, but sometimes you need to draw things manually.
Upvotes: 3