What is the best practice for creating custom UIView's? - ios

For creating custom views i have three options.
Override
func drawRect(_ rect: CGRect)
Add sub-layers to the view's Layer.
Do both.
What is the best practice? why would i override drawRect if i can draw everything in a sub-layer (With an easier API)?
Thanks

Rendering in drawRect means that you are using the CPU to draw your view using Core Graphics.
If you can use a composition of CALayer sub-layers, then that is almost always the better option as the heavy lifting is then done by GPU.
On top of that, drawRect is called on the main thread, and if your drawing code isn't fast your app will be less responsive (of course you can use a background thread to solve this problem, but you will still be using the CPU to draw your bitmap).

Related

How does a UIView/CALayer render itself without drawRect:?

In Apple's Core Animation documentation, it says there are two rendering paths involved. From what I know, CALayer caches bitmap data of a UIView content. There are two ways of providing content of a CALayer. One is implementing drawRect: or other CALayer drawing methods, the other is setting a bitmap to the property contents of CALayer.
Here I'm wondering, what happens behind the scene if neither of the above two things is done? I believe there is a private drawing path UIView uses in this situation. What is this private drawing path consists of? How does it work?
The crux of CALayer is that it's GPU-backed. In modern graphics and animation, you want to minimize the number of times your bitmap data crosses between the CPU and the GPU. These operations are costly.
CALayer always uses a private drawing path, whether you use setContents: or drawRect:. In fact, the underlying plumbing of CALayer handles both of these in essentially the same way. When you setContents: , CALayer takes the image you gave it, and uploads it to the GPU via OpenGL (probably nowadays Metal) calls. When you drawRect: the CALayer gives you a context into which you can draw, and then it does the same thing with the bitmap data.
If you don't set contents or implement drawRect, you can still do things like set the layer's background color, border, corner radius, etc. This is being rendered by CALayer's GPU-based private drawing path.
CALayer does not draw any of its content using drawRect:. Only view based drawing techniques like Core Graphics use drawRect: but the only problem with this ways of things is that it is done on the CPU and the main thread making it an expensive process. So instead, Core Animation manipulates a cached bitmap of your apps content in the graphics hardware directly which is far much more optimised. You update or provide the initial contents for a Core Animation layer through one of its delegates (displayLayer: or drawLayer:inContext) or using the contents property as you have mentioned. All layer objects in Core Animation are derived from CALayer.
CALayer is simply a layer object belonging to Core Animation which in itself is simply a support system for UIView or subclasses of UIView. Core Animation is not a drawing technology in the sense it cannot create primitive shapes like Quartz, Open GL ES and Metal can. Instead, Core Animation allows you to manipulate an already existing view and it does this by caching the bitmap data of a UIView and sending this off to the graphics hardware to be manipulated. We say Core Animation is a support system and all its work relies on using layer objects of which CALayer is the main type. It can only do this of course if a view has a layer and a view does not actually need a layer to exist. However, in iOS all views come with a layer attached by default. We say views in iOS are "layer backed". In MacOS, you need to actually add Core Animation support for views.
The actual drawing of the contents of a CALayer happens in a few ways. The first is changing the contents property of the CALayer as you have mentioned and you do this by giving it a CGImageRef. The second is by implementing or overriding in a subclass the CALayer delegate displayLayer: which creates a bitmap and sets it to the content property of a layer. The third is by implementing or overriding in a subclass the CALayer delegate drawLayer:inContext which creates a bitmap, creates a graphics context to draw into that bitmap, and then calls your delegate method to fill the bitmap.
In iOS we do not usually worry about how the content of our view's layers are rendered. Since all views are layer backed, iOS manages how to render these views in the most efficient way possible using the methods I've just described. This is an optimisation to save you time and it makes layers very easy to use. You'll usually worry about overriding these delegates or subclassing them if you are developing for MacOS where views are not always layer backed. You might also worry about this if you decide not to use the default CALayer in iOS, for example you might change a view's layer from CALayer to CAMetalLayer. Or perhaps if you are looking for a performance optimisation and even this in a small number of cases.
There are three ways to provide content to a layer.
- Assign an image object directly to the layer object’s contents property.
- Assign a delegate object to the layer and let the delegate draw the layer’s content.
- Define a layer subclass and override one of its drawing methods to provide the layer contents yourself.
If we don't implement drawRect: or setting the contents property or subclass the layer, it will use the default way which is the second one to provide content to a Layer-backed views's layer. The layer will capture the content of the view and render it.

Best way to handle autoresizing of UIView with custom drawing

I'm working on a custom view, that has some specific Core Graphics drawings. I want to handle the view's autoresizing as efficiently as possible.
If I have a vertical line drawn in UIView, and the view's width stretches, the line's width will stretch with it. I want to keep the original width, therefore I redraw each time in -layoutSubviews:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
// ONLY drawing code ...
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self setNeedsDisplay];
}
This works fine, however I don't think this is a efficient approach - unless CGContext drawing is blazing fast.
So is it really fast? Or is there better way to handle view's autoresizing? (CALayer does not support autoresizing on iOS).
UPDATE :
this is going to be a reusable view. And its task is to draw visual representation of data, supplied by the dataSource. So in practice there could really be a lot of drawing. If it is impossible to get this any more optimized, then there's nothing I can do... but I seriously doubt I'm taking the right approach.
It really depends on what you mean by "fast" but in your case the answer is probably "No, CoreGraphics drawing isn't going to give you fantastic performance."
Whenever you draw in drawRect (even if you use CoreGraphics to do it) you're essentially drawing into a bitmap, which backs your view. The bitmap is eventually sent over to the lower level graphics system, but it's a fundamentally slower process than (say) drawing into an OpenGL context.
When you have a view drawing with drawRect it's usually a good idea to imagine that every call to drawRect "creates" a bitmap, so you should minimize the number of times you need to call drawRect.
If all you want is a single vertical line, I would suggest making a simple view with a width of one point, configured to layout in the center of your root view and to stretch vertically. You can color that view by giving it a background color, and it does not need to implement drawRect.
Using views is usually not recommended, and drawing directly is actually preferred, especially when the scene is complex.
If you see your drawing code is taking a considerable toll, steps to optimize drawing further is to minimize drawing, by either only invalidating portions of the view rather than entirely (setNeedsDisplayInRect:) or using tiling to only draw portions.
For instance, when a view is resized, if you only need to draw in the areas where the view has changed, you can monitor and calculate the difference in size between current and previous layout, and only invalidate regions which have changed. Edit: It seems iOS does not allow partial view drawing, so you may need to move your drawing to a CALayer, and use that as the view's layer.
CATiledLayer can also give a possible solution, where you can cache and preload tiles and draw required tiles asynchronously and concurrently.
But before you take drastic measures, test your code in difficult conditions and see if your code is performant enough. Invalidating only updated regions can assist, but it is not always straightforward to limit drawing to a provided rectangle. Tiling adds even more difficulty, as the tiling mechanism requires learning, and elements are drawn on background threads, so concurrency issues also come in play.
Here is an interesting video on the subject of optimizing 2D drawing from Apple WWDC 2012:
https://developer.apple.com/videos/wwdc/2012/?include=506#506

Animating custom Bezier paths by looping drawRect

I have custom drawing code that uses bezier paths , gradients and strokes to perform my drawing. I want to run custom animations by looping drawRect and changing the values of properties on the bezier paths.
I have looked at using CAShapeLayer (UIView animation in drawrect) but that doesn't seem to cut it for me. My drawing code is quite complex, runs into a few hundred lines and all the drawing is done through bezier paths and gradients. Changing the drawings to a CAShapeLayer and then adding colors and gradients to it will be very time consuming!
I know that it is not recommended by Apple to explicitly call drawRect rather to use setNeedsDisplay to call draw rect (How to use DrawRect correctly). But the problem with doing that is i experience slight difference in the animation each time (very minute though). It may have something to do with the fact that setNeedsDisplay schedules drawRect to be called on the run loop but doesn't directly call it by itself.
I want to know what strategies i can use to use to loop drawRect and achieve synchronized perfectly timed animations each time. Is it possible to do this?
Both Animating Pie Slices Using a Custom CALayer and Animating Custom Layer Properties by Rob Napier are two good resources to learn how to make custom animations when you are doing completely custom drawing inside drawInContext:.
If you still feel that setting up an external mechanism to synchronize the drawing then I suggest that you look at CADisplayLink.

drawing shadow using core graphic and using CALayer

As far as I know we can use core graphic such as CGContextSetShadowWithColor to draw a shadow. However, we can also use CALayer to show the shadow as well.
Question :
what are the differences between 2 of them. Are there any rules to determine when we use core graphic to draw a or when we use CALayer to do the job
I would have to say that using CoreAnimation is always preferred over CoreGraphics, since it's more high level, and abstracts the low-level details of drawing the shadow. (It may also allow apple to optimize the shadow drawing without hurting your code syntax).
However, there are times where you are overriding drawRect: anyways, and you have very specific use for the shadow, not the whole view's layer. You might wanna use CoreGraphics shadows here.
One last note, CoreAnimation gradients are much faster when rendering, take my word for it. I used it on UITableViewCell, and the scroll performance significantly increased, as opposed to using CoreGraphics Gradients. That comes at a price, though. It's a bit worse-looking.

CGContextDrawLinearGradient versus cagradientlayer?

What is the difference between CGContextDrawLinearGradient, called in a UIView's drawRect method, and a CAGradientLayer? How do they compare performance wise? What is the best practice for creating gradient views? I'd really like a nice explanation of how they relate to each other and why one is better performance than the other.
Thanks.
If you just want a box with a gradient in it then performance isn't really an issue. You should go with whatever is simplest to implement for your particular requirements.
Adding a CAGradientLayer means you don't have to create a view subclass, you can just add the layer to an existing view. The setup is also slightly easier, since you don't need to worry about frame sizes or any c-style core graphics functions. You can also add rounded corners, shadows etc without too much effort.
However, if you want more than one gradient view, a subclass might be a good idea, so you can just instatiate new ones.
So, unfortunately, there isn't a clear cut answer to your question. Neither is definitively better. If you are concerned with performance, implement both and test using instruments.

Resources