When should I go with core graphics over images for making a custom UIButton? Is core graphics faster? Other than resolution independence, are there any other major benefits?
Core Graphics uses what's called a “painter's model”. When you draw into a context, it's almost like making a painting. You lay down a path and fill it, and then lay down another path on top and fill it. You can't change the pixels that have been laid down, but you can paint over them.
Swift Core Graphics. Harness the power of Quartz technology to perform lightweight 2D rendering with high-fidelity output. Handle path-based drawing, anti-aliased rendering, gradients, images, color management, PDF documents, and more.
SwiftUI's button is similar to UIButton , except it's more flexible in terms of what content it shows and it uses a closure for its action rather than the old target/action system. To create a button with a string title you would start with code like this: Button("Button title") { print("Button tapped!") }
Pros of Core Graphics:
Pros of images:
As for running time, I am not sure. I would guess that CG would be faster for simple drawing, where most of the pixels aren't changed, but images would be faster for more complex drawing where most of the pixels are changed (Assuming you use the PNG format, so it gets optomized. Otherwise, CG would probably always be faster).
As a compromise, you could draw into an image once, and use that image for future drawing. This would allow you to get some of the benefits from each.
Additional thoughts to ughoavgfhw's comment:
Images can be cached (like when you use [UIImage imageNamed:]
). So you even won't use more memory for new buttons, except the first one displayed. (And no allocations, except memory for a new pointer).
You can use stretchable images for button creation, and avoid some (not all and not always) problems with resolution dependence:
UIImage *myImg = [UIImage imageNamed:@"myImg.png"];
UIImage *myImgStretchable = [myImg stretchableImageWithLeftCapWidth:10 topCapHeight:10];
[myButton setBackgroundImage:myImgStretchable forState:UIControlStateNormal];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With