Ios--core Animation Knowledge Excerpt (I.)

Source: Internet
Author: User

This article is a excerpt from the key paragraphs of the http://www.cocoachina.com/ios/20150104/10814.html article, with the need to read the original

The relationship between Calayer and UIView:

The Calayer class is conceptually similar to UIView and is also a rectangular block managed by a hierarchical tree, and can also contain some content (like pictures, text, or background colors) to manage the placement of sublayers. They have some methods and properties for animating and transforming. The biggest difference from UIView is that Calayer does not handle user interaction.

Calayer does not know the specific response chain (the mechanism that iOS uses to transmit touch events through a view-level relationship), so it does not respond to events, even if it provides a way to determine if a contact is within the range of the layer (see chapter III, "Geometry of the Layer")

In fact, the layers behind these are the ones that are really used to display and animate on the screen, and UIView is just an encapsulation of it, providing some of the specific features of iOS that are similar to touch, as well as the advanced interface of the core animation underlying approach.

But why is iOS providing two parallel hierarchies based on UIView and Calayer? Why not use a simple hierarchy to handle everything?

This is due to separation of duties, which avoids a lot of duplication of code. On iOS and Mac OS two platforms, there are many differences between event and user interaction, multi-touch based user interface and mouse-based keyboard are essential differences, which is why iOS has Uikit and UIView, but Mac OS has AppKit and nsview reasons. They are functionally similar, but there are significant differences in implementation.

Drawing, layout, and animation, by contrast, are similar to the concept of iphone and ipad touch screens like Mac notebooks and desktop families. By separating the logic of this function and applying it to the standalone core animation framework, Apple can share code between iOS and Mac OS, making it easier for Apple's own OS development team and third-party developers to develop two platforms.

Calayer can't handle touch events, what views can't be done?
    • Shadows, rounded corners, colored borders

    • 3D transformations

    • Non-rectangular Range

    • Transparent matte

    • Multi-stage Nonlinear animation

Contents property

The type of this property is defined as an ID, which means it can be any type of object. However, in practice, if you give contents not cgimage, then the layer you get will be blank .

Contents this strange performance is caused by the historical causes of Mac OS. It is defined as the ID type because on Mac OS systems, this property works on values of cgimage and nsimage types. If you try to assign the value of UIImage to it on the iOS platform, you can only get a blank layer. Some iOS developers who are beginning to know core animation may be confused about this.

Contentsscale Property

When handling a homestay map in code, it is important to remember to manually set the Contentsscale property of the layer, otherwise your picture is not displayed correctly on the retina device. The code is as follows: Layer.contentsscale = [UIScreen mainscreen].scale;

Contentgravity Property

How it works and how it's scaled

Contentsrect Property

The Contentsrect property of Calayer allows us to display a subdomain of the homestay map in the layer border. This involves how the picture is displayed and stretched, so it's much more flexible than contentsgravity.

Unlike Bounds,frame, Contentsrect is not calculated by point, it uses unit coordinates, and the unit coordinates are specified between 0 and 1, which is a relative value (pixels and points are absolute values). So they are relative to the size of the homestay map. iOS uses the following coordinate systems:

    • Point-the most common coordinate system in iOS and Mac OS. A point is like a virtual pixel, also known as a logical pixel. On a standard device, a point is a pixel, but on a retina device, a point is equal to 2*2 pixels. iOS uses dots as the coordinate measurement system for screens to have consistent visual effects on retina devices and common devices.

    • Pixel--physical pixel coordinates are not used for screen layout, but still have a relative relationship to the picture. UIImage is a screen resolution solution, so specify a point to measure the size. But some of the underlying images show that pixels are used like cgimage, so you have to be aware that they show different sizes on retina devices and normal devices.

    • Units-for displays related to image size or layer boundaries, the unit coordinates are a convenient measure and do not need to be adjusted when the size changes. The unit coordinates are used much in OpenGL's texture coordinate system, and the unit coordinates are used in the Core animation.

The default contentsrect is {0, 0, 1, 1}, which means that the entire homestay map is visible by default, and if we specify a smaller rectangle, the picture will be cropped (2.6) Figure 2.6 A custom contentsrect (left) and previously displayed content (right)

Typically, a picture can be packaged and integrated into a large image once loaded. There are a number of benefits to this: memory usage, loading time, rendering performance, and so on, compared to loading different images multiple times .

The game engine into cocos2d uses the flattening technique, which uses OpenGL to display pictures. But we can use flattening in a common Uikit application, right! is to use Contentsrect

First, we need a flattened chart--a large picture with a smaller flattened figure. 2.7 is shown below:

Next, we'll load and display these flattener images in the app. The rule is simple: load our big picture as usual, then assign it to the contents of four separate layers, then set the contentsrect of each layer to get rid of the parts we don't want to show.

Some additional views are needed in our project. (To avoid too much code.) We will use Interface Builder to visit their location, if you would like to do it in code. Listing 2.3 has the required code, and figure 2.8 shows the results

@interfaceViewcontroller () @property (nonatomic, weak) Iboutlet UIView*Coneview, @property (nonatomic, weak) Iboutlet UIView*Shipview, @property (nonatomic, weak) Iboutlet UIView*Iglooview, @property (nonatomic, weak) Iboutlet UIView*Anchorview;@end@implementationViewcontroller- (void) Addspriteimage: (UIImage *) image withcontentrect: (cgrect) rect? Tolayer: (Calayer *) layer//Set Image{layer.contents= (__bridgeID) image.  Cgimage; //Scale contents to fitLayer.contentsgravity =Kcagravityresizeaspect; //Set ContentsrectLayer.contentsrect =rect;}- (void) viewdidload {[Super viewdidload];//Load Sprite SheetUIImage *image = [UIImage imagenamed:@"Sprites.png"]; //Set Igloo Sprite[Self addspriteimage:image withcontentrect:cgrectmake (0,0,0.5,0.5) ToLayer:self.iglooView.layer]; //Set Cone Sprite[Self addspriteimage:image withcontentrect:cgrectmake (0.5,0,0.5,0.5) ToLayer:self.coneView.layer]; //Set anchor Sprite[Self addspriteimage:image withcontentrect:cgrectmake (0,0.5,0.5,0.5) ToLayer:self.anchorView.layer]; //Set Spaceship Sprite[Self addspriteimage:image withcontentrect:cgrectmake (0.5,0.5,0.5,0.5) ToLayer:self.shipView.layer];}@end

flattening not only gives the app a neat way to load, it also effectively improves load performance (a larger picture is faster than multiple small plots), but if there are manual arrangements, they still have some inconvenience, If you need to make some size changes or other changes in an already created product or diagram, it's a hassle.

Contentscenter Property

Contentscenter is actually a cgrect that defines a fixed border and an area to stretch on the layer. Changing the value of Contentscenter does not affect the display of the homestay map, unless the size of the layer changes, you can see the effect.

By default, Contentscenter is {0, 0, 1, 1}, which means that if the size (determined by conttensgravity) changes, the homestay map will be stretched evenly. But if we increase the value of the origin and reduce the size. We'll create a border around the picture. Figure 2.9 shows the effect of Contentscenter set to {0.25, 0.25, 0.5, 0.5}.

Set in IB:

custome Drawing

The value assigned to contents Cgimage is not the only way to set up a homestay map. We can also directly draw a homestay map with the core graphics directly. Ability to customize drawing by inheriting UIView and implementing-drawrect: Method.

If you don't need a homestay map, do not create this method, which can result in wasted CPU resources and memory, which is why Apple recommends that you do not write an empty-drawrect in the subclass if you do not have a custom-drawn task: method.

-drawrect when the view appears on the screen: The method is automatically called. -drawrect: The code inside the method uses the core graphics to draw a homestay map , and then the content is cached until it needs to be updated (usually because the developer calls the-setneedsdisplay method, Some view types are automatically redrawn, such as the Bounds property, although the property values that affect the performance effect are changed. Although-drawrect: The method is a UIView method, the fact is that the underlying calayer is arranged to redraw the work and save the resulting picture.

When it needs to be redrawn, Calayer will ask its agent to give him a homestay map to display. It does this by invoking the following method:

1 (void)displayLayer:(CALayerCALayer *)layer;

Take advantage of this opportunity, if the agent wants to set the contents property directly, it can do so, otherwise there is no other way to call. If the agent does not implement the-displaylayer: method, Calayer will instead attempt to invoke the following method:

1 - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;

Before calling this method, Calayer created an empty homestay map of the appropriate size (size determined by bounds and Contentsscale) and a drawing context for the core graphics, which prepares for drawing the homestay map, which he passed in as a CTX parameter.

@implementationViewcontroller- (void) viewdidload{[Super Viewdidload]; ?//Create SublayerCalayer *bluelayer =[Calayer layer]; Bluelayer.frame= CGRectMake (50.0f,50.0f,100.0f,100.0f); Bluelayer.backgroundcolor=[Uicolor Bluecolor].  Cgcolor; //set controller as layer delegateBluelayer.Delegate=Self ; //ensure that layer backing image uses correct scaleBluelayer.contentsscale = [UIScreen mainscreen].scale;//Add layer to our view[Self.layerView.layer Addsublayer:bluelayer]; //Force layer to redraw[bluelayer display];}- (void) Drawlayer: (Calayer *) layer Incontext: (cgcontextref) ctx{//draw a thick red circleCgcontextsetlinewidth (CTX,10.0f); Cgcontextsetstrokecolorwithcolor (CTX, [Uicolor Redcolor].  Cgcolor); Cgcontextstrokeellipseinrect (CTX, layer.bounds);}@end
    • We have explicitly called-display on the Bluelayer. Unlike UIView, when a layer is displayed on the screen, Calayer does not automatically redraw its contents. It gives the developer the power to redraw the decision.

Now you understand calayerdelegate and know how to use it. But unless you create a separate layer, you have little chance of using the Calayerdelegate protocol. Because when UIView creates its host layer, it automatically sets the layer's delegate to itself and provides a-displaylayer: the implementation, all the problems are gone.

Geometric correlation

Anchor Point

As mentioned previously, both the center property of the view and the position property of the layer specify the position relative to the parent layer anchorpoint. The anchorpoint of a layer controls the position of its frame by position, and you can think of Anchorpoint as a handle to move the layer.

By default, Anchorpoint is positioned at the midpoint of the layer, so the layer will be centered at this point. The Anchorpoint property is not exposed by the UIView interface, which is why the position property of the view is called "center". But the layer's anchorpoint can be moved, for example, you can put it in the upper-left corner of the layer frame, so the contents of the layer will move in the direction of the lower-right corner of the position (Figure 3.3), not centered.

Note in Figure 3.3, when the changed Anchorpoint,position property remains fixed, the value does not change, but the frame moves.

And on what occasion does it need to change anchorpoint? Since we can change the position of the layer at will, wouldn't it be confusing to change the anchorpoint? To illustrate this, let's take a practical example and create a project that simulates an alarm clock.

-(void) viewdidload {    [super Viewdidload];     // Adjust anchor points    Self.secondHand.layer.anchorPoint = Cgpointmake (0.5f0.9f);      = Cgpointmake (0.5f0.9f);      = Cgpointmake (0.5f0.9f);     // Start Timer}

Hit testing

Note When you call the layer's-hittest: method, the order of the calculations is strictly dependent on the layer order in the layer tree (similar to the UIView handling event). The previously mentioned Zposition properties can significantly alter the order of the screen layers, but cannot change the order in which the events are passed.

This means that if you change the z-axis order of the layer, you will not be able to detect the front-most view-click event because it is obscured by another layer, although its zposition value is small, but in the order of the layer tree.

Ios--core Animation Knowledge Excerpt (I.)

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.