IOS --- connection and difference between UIView and CALayer

Source: Internet
Author: User

IOS --- connection and difference between UIView and CALayer

UIView is the basis of interface elements in iOS systems. All interface elements are inherited from it. UIView itself is completely implemented by CoreAnimation. the real drawing part is managed by a CALayer class. UIView is more like a CALayer manager, so accessing its plotting and coordinate-related attributes, such as frame and bounds, is actually accessing its CALayer-related attributes. therefore, animation effects can be implemented on all the UIView subclass.
UIView inherits from UIResponder and can receive and respond to events. It is responsible for managing the display content. CALayer inherits from NSObject and cannot respond to events. It is responsible for drawing the display content.

Layer attribute of UIView

Obtain the layer attribute of UIView:

CALayer *layer = self.view.layer;

The layerClass method of UIView returns the class used by the layer. You can override this method so that the inheritance class of UIView is displayed using the specified CALayer. The following code allows OpenGL to be used for rendering.

+ (Class)layerClass {     return [CAEAGLLayer class];}

For UIViewController, you can perform the following operations to allow its UIView to be drawn using OpenGL. The level structure of CALayer is similar to that of UIView. The role of addSublayer and addSubview is similar.

CAEAGLLayer *eaglLayer = [CAEAGLLayer layer];eaglLayer.frame = self.view.frame;eaglLayer.opaque = YES;eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],kEAGLDrawablePropertyRetainedBacking,kEAGLColorFormatRGBA8,kEAGLDrawablePropertyColorFormat, nil];[self.view.layer addSublayer:eaglLayer];

When CALayer is updated and cannot be displayed immediately, you can use the setNeedsDisplay method to re-paint the display.

[MyLayer setNeedsDisplay]; // update the local region [myLayer failed: CGRectMake (100,100, 50, 50)]; // CoreGraphics can directly use renderInContext [myLayer renderInContext: UIGraphicsGetCurrent ()];
CALayer

A UIView can have multiple calayers. The size and style of the UIView are provided by the Internal CALayer. each CALayer displays an effect. Therefore, you can add CALayer with multiple effects to enhance the display capability of UIView. for example, UIView itself cannot set rounded corners and other effects, while CALayer can set borders, rounded corners, shadows, transformation and deformation. both have a tree structure, CALayer has subLayers, and UIView has subViews.

Contents attributes
CALayer *aLayer = [[CALayer alloc] init;aLayer.contents = [[UIImage imageNamed:@testImage] CGImage];aLayer.contentsGravity = kCAGravityResizeAspectFill;

If you use an image to assign a value to contents, it must be CGImage.
You can set contentsGravity to set its display mode, which is equivalent to the contentMode of UIView. For example, kCAGravityResizeAspectFill is full. KCAGravityResizeAspect is the size of the display itself.
If the image size exceeds the value of CALayer, you can use maskToBounds to crop the image and cut out the excess image size (with rounded corners ).

ContentsRect

Used to crop an image. The default contentsRect value is {0, 0, 1, 1}, indicating that the entire image is visible by default. if we change to {0, 0, 0.5, 0.5}, the image will be cropped out of 1/4 in the upper left corner.

CALayer Effect
ALayer. backgroundColor = [[UIColor redColor] colorWithAlphaComponent: 0.2] CGColor]; // border aLayer. boardColor = [[UIColor blueColor] CGColor]; aLayer. boardWidth = 2.0; // rounded aLayer. cornerRadius = 10.0; // shadow aLayer. shadowColor = [[UIColor greenColor] CGColor]; aLayer. shadowOpacity = 0.5; aLayer. shadowOffset = CGSizeMake (2, 1); [self. view. layer addSublayer: aLayer];

CornerRadius and shadowColor cannot appear at the same time. Therefore, you can use two overlapping uiviews to display the rounded corner and shadow respectively.

Transform

QuartzCore's CATransform3D provides rotation, scaling, and skew conversion effects.
Add a 3D or affine transform as follows:

myView.layer.transform = CATransform3DMakeScale(-1.0, -1.0, 1.0);CGAffineTransform transform = CGAffineTransformMakeRotation(45.0);myView.layer.affineTransform = transform;

You can use [layer removeAllAnimations] to cancel an animation.
For details, refer to swift's twenty-four ----- CoreAnimation (1) CALayer.

Layer Tree

CALayer maintains three layer trees, namely, presentLayer tree (animation Tree), mode Layer Tree (model Tree), and Render tree (rendering Tree). During iOS animation, we modify the animation attributes. In fact, the animation is actually the attribute value of the Layer presentLayer, and the final display on the Interface actually provides the modeLayer of the UIView.

Difference between UIView and CALayer

UIView is inherited from UIResponder. Its main feature is that it can respond to touch events. CALayer manages the actual layer content and does not render it directly to the screen. What everyone does is different. There are two things that do not affect each other.

Event Response

Simply regard CALayer as a special UIView that can only be displayed and cannot respond to events; or regard UIView as a CALayer that can receive and respond to events.
UIKit uses UIResponder as the response object to respond to and process the events passed by the system.
UIApplication, UIViewController, UIView, and all the UIKit classes derived from UIView (including UIWindow) are inherited directly or indirectly from the UIResponder class. UIResponder defines interfaces for processing various events and passing events.. Handle events such as touchesBegan: withEvent:, touchesMoved: withEvent:, touchesEnded: withEvent.
WhileCALayer directly inherits from NSObject and does not have an interface for event processing..
For more information about UIResponder, see the following two articles:
1. Responder Chain Analysis
2. View and window architecture

Frame, position, bounds call

The frame of a CALayer is determined by its anchorPoint, position, bounds, and transform. The frame of a UIView simply returns the frame of CALayer, similarly, the center and bounds of UIView simply return the Position and Bounds attributes of CALayer.

Mechanism and Policy Separation

UIView mainly manages the displayed content, while CALayer mainly draws the displayed content. UIView is CALayerDelegate of CALayer. In the proxy method, [UIView (CALayerDelegate) drawLayer: inContext] calls the drawRect method of UIView to draw the UIView content. the display content of UIView is implemented by the Internal CALayer: display Method.
Programming Problems can be extracted from the mechanism and policy. Once the mechanism is implemented, it will be rarely changed, but the policy will be optimized frequently. CALayer can also be seen as a mechanism that provides layer rendering. the header file of CALayer is basically unchanged, while UIView can be seen as a policy with many changes. The more underlying the mechanism, the more stable the mechanism is. The mechanism and policy separation can reduce the amount of code to be modified, especially the underlying code, which can improve the system stability. UIView masks most CALayer interfaces and extracts and constructs easier-to-use frame and animation implementations, making it easier to get started.

CALayer generates implicit animation by default.

CALayer supports implicit animation for default Attribute Modification. For every UIView, there is a layer, which is called RootLayer rather than the root layer of the View. When we modify the properties of the UIView, the default animation will not be generated, but will be directly modified for the individual layer attribute. The default animation time is 0.25 s. that is, when you perform an iOS animation, an implicit animation is generated by default when you modify the attributes of a non-RootLayer (such as the position and background color), but not the UIView.
When performing an animation on the CALayer of the UIView, The UIView acts as the proxy of the CALayer, and CALayer requests the corresponding animation action from the UIView through actionForLayer: forKey.
In "How to Animate Layer-Backed Views" in the Core Animation programming guide, I explained why:

By default, layer animation is disabled for UIView, but they are re-enabled in the animation block.
The reason is that when any animation layer attribute changes, the layer will find and run the appropriate 'action' to implement this change. In Core Animation terminology, such an Animation is collectively referred to as an action or CAAction ).
Layer sends an actionForLayer: forKey: message to its delegate to ask for an action that corresponds to a property change. Delegate can respond by returning one of the following:
It can return an action object. In this case, the layer uses this action.
It can return an nil, so that the layer will continue searching elsewhere.
It can return an NSNull object, telling the layer that no action is required, and the search will also stop.
When a layer supports a view, the view is its delegate;
This part of the specific content reference: http://objccn.io/issue-12-4/Key Content

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.