[IOS animation]-calayer layer geometry

Source: Internet
Author: User

Layer geometry

Don't come here if you're not familiar with geometry --The signature of the entrance to Plato's College.

In Chapter Two, we describe the image behind the layer, and some properties that control the coordinates and rotation of the layer. In this chapter, we'll look at how the inside of the layer controls position and size based on the parent layer and the sibling layer. We will also cover how to manage the geometry of the layer and how it is affected by auto-adjustment and automatic layout.

Layout

UIViewThere are three more important layout attributes: frame , bounds and center , correspondingly, CALayer called frame , bounds and position . To be clear, the layer uses "position" and the View uses "center", but they all represent the same value.

frameRepresents the outer coordinates of the layer (that is, the space occupied on the parent layer), the bounds internal coordinates ({0, 0} are usually the upper-left corner of the layer), center and position all represent the location relative to the parent layer anchorPoint . anchorPointproperties will be introduced later, so it's good to think of it as the center point of the layer. Figure 3.1 shows how these properties depend on each other.

Figure 3.1 UIView and CALayer the coordinate system

Views frame , bounds and center properties are simply access methods , and when manipulating views, they frame are actually changing the view below CALayer the view frame , and cannot be changed independently of the layer frame .

For a view or a layer, frame it is not a very clear attribute, it is actually a virtual property, is based on bounds , position and transform calculated, so when any of the values change, frame will change. Conversely, changing the value of a frame also affects the values in them.

Remember that when you transform a layer, such as rotation or zooming, it frame actually represents a rectangular area that covers the entire axis aligned after the layer is rotated, meaning frame that the width and height may bounds no longer be the same (Figure 3.2)

Figure 3.2 Rotating a view or a property after a layer frame

Anchor Point

As mentioned before, both the properties of the view center and the properties of the layer position specify the anchorPoint position relative to the parent layer. The layer is anchorPoint passed position to control its frame position, and you can think of it anchorPoint as a handle to move the layer.

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

Figure 3.3 anchorPoint The effect of the change

Similar to the attributes mentioned in the second chapter, described by the unit coordinates, that is, the contentsRect contentsCenter anchorPoint relative coordinates of the layer, the upper left corner of the layer is {0, 0}, the lower right corner is {1, 1}, so the default coordinates are {0.5, 0.5}. anchorPointyou can place it outside the layer range by specifying that the X and Y values are less than 0 or greater than 1.

Note in Figure 3.3, when the change is made anchorPoint , the position property remains fixed and the value does not change, but frame it moves.

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

The clock face and clock are made up of four images (Figure 3.4), for the sake of simplicity, we still load and load images in a traditional way, using four UIImageView instances (you can, of course, set up images of their layers with normal views contents ).

Figure 3.4 Four pictures of clock faces and clocks

The components of the alarm clock are arranged by IB (Figure 3.5), which are nested within a container view, and the auto-adjust and auto-layout are disabled. This is because auto-tuning affects the view frame , and as shown in Figure 3.2, when the view is rotated, it frame changes, which can lead to some layout failures.

We used NSTimer to update the alarm clock, using the properties of the view transform to rotate the clock (if you are not familiar with this property, do not worry, we will be in the 5th Chapter "transformation" in detail), the specific code shown in Listing 3.1

Figure 3.5 Layout The alarm view in Interface Builder

List 3.1 Clock

@interface Viewcontroller () @property (nonatomic, weak) Iboutlet Uiimageview *hourhand; @property (nonatomic, weak) Iboutlet Uiimageview *minutehand; @property (nonatomic, weak) Iboutlet Uiimageview *secondhand; @property (Nonatomic,    Weak) Nstimer *timer, @end @implementation viewcontroller-(void) viewdidload{[Super Viewdidload]; Start Timer Self.timer = [Nstimer scheduledtimerwithtimeinterval:1.0 target:self selector: @selector (tick) userinfo:n                  Il repeats:yes];    ? Set initial hand positions [self tick];} -(void) tick{//convert time to hours, minutes and seconds nscalendar *calendar = [[Nscalendar alloc] Initwithcalend    Aridentifier:nsgregoriancalendar]; Nsuinteger units = Nshourcalendarunit | Nsminutecalendarunit |    Nssecondcalendarunit;    nsdatecomponents *components = [Calendar components:units fromdate:[nsdate Date]];    CGFloat hoursangle = (components.hour/12.0) * M_PI * 2.0; Calculate hour hand angle//calculate minute hand angle CGFLoat Minsangle = (components.minute/60.0) * M_PI * 2.0;    Calculate second hand angle cgfloat secsangle = (components.second/60.0) * M_PI * 2.0;    Rotate hands Self.hourHand.transform = cgaffinetransformmakerotation (Hoursangle);    Self.minuteHand.transform = Cgaffinetransformmakerotation (Minsangle); Self.secondHand.transform = Cgaffinetransformmakerotation (Secsangle);} @end

Running the project looks a little strange (Figure 3.6), because the picture of the clock revolves around the center, which is not a fulcrum we expect.

Figure 3.6 clock face, and misaligned clock hands

You might think that you can adjust the position of the pointer image in Interface builder, but it doesn't work, because if you don't put it in the middle of the clock, it doesn't rotate correctly.

It may be a solution to add a transparent space at the end of the picture, but it will make the picture bigger and consume more memory, which is not elegant.

A better approach is to use anchorPoint attributes, and let's -viewDidLoad add a few lines of code to the method to do some panning for each clock pointer anchorPoint (listing 3.2), and figure 3.7 shows the correct result.

Listing 3.2

-(void) viewdidload {    [super viewdidload];    Adjust anchor points    Self.secondHand.layer.anchorPoint = Cgpointmake (0.5f, 0.9f);     Self.minuteHand.layer.anchorPoint = Cgpointmake (0.5f, 0.9f);     Self.hourHand.layer.anchorPoint = Cgpointmake (0.5f, 0.9f);    Start Timer}

Figure 3.7 clock face, and correctly aligned clock hands

Coordinates

As with views, layers are placed hierarchically in the layer tree relative to the parent layer, and one layer position depends on its parent layer, and bounds if the parent layer moves, all its sublayers will move along.

This makes it easier to place layers, because you can move the root layer to move its sublayers as a whole, but sometimes you need to know the absolute position of a layer, or the position of the other layer, rather than the position of its current parent layer.

CALayerSome tool class methods are provided for layer transformations between different coordinate systems:

-(Cgpoint) Convertpoint: (cgpoint) point fromlayer: (Calayer *) layer; -(Cgpoint) Convertpoint: (cgpoint) point tolayer: (Calayer *) layer; -(CGRect) Convertrect: (cgrect) rect fromlayer: (Calayer *) layer;-(CGRect) Convertrect: (cgrect) rect tolayer: (CALayer *) Layer

These methods can convert a point or rectangle defined in one layer coordinate system to a point or rectangle under another layer coordinate system.

The geometry of the flip

Generally speaking, on iOS, a layer is located in the upper- position left corner of the parent layer, but on Mac OS, it is usually located in the lower-left corner. The Core animation can be geometryFlipped adapted to both cases by attributes, which determines whether the coordinates of a layer are flipped vertically relative to the parent layer, which is a BOOL type. On iOS by setting it to YES mean that its sublayers will be flipped vertically, i.e. it will be typeset along the bottom rather than the usual top (all its sublayers are the same, unless geometryFlipped you set their properties YES ).

Z axis

And UIView the strict two-dimensional coordinate system is different, CALayer exists in a three-dimensional space. In addition to the attributes we have discussed, position anchorPoint CALayer There are two other properties, zPosition and anchorPointZ both are floating-point types that describe the position of the layer on the z-axis.

Note that there is no deeper attribute to describe the width and height of the bounds layer is a completely flat object, you can think of them like a page two-dimensional hard paper, glue into a hole, like three-dimensional structure of origami.

zPositionProperties are not commonly used in most cases. In the fifth chapter, we will deal with CATransform3D , you will know how to move and rotate the layer in three-dimensional space, in addition to making transformations, zPosition the most useful function is to change the layer display order .

In general, layers are drawn according to the order in which they sublayers appear, which is the so-called Painter's algorithm --like a painter painting on a wall--the layers that are drawn will cover the previous layer, but by adding layers zPosition , you can move the layer toward the camera Front, so it is in front of all other layers (or at least the layer that is smaller than its zPosition value).

Here the so-called "camera" is actually a perspective relative to the user, there is nothing to do with the built-in camera behind the iphone.

Figure 3.8 shows a view within the interface Builder, as you can see, that the views that appear first in the view-level green are drawn behind the red view.

Figure 3.8 The Green view is drawn behind the red view in the view hierarchy

We want to be able to show the order of the drawings in real applications, as well, if we raise the Green View zPosition (listing 3.3), we'll see that the order is reversed (figure 3.9). In fact, there is no need to add too much, the view is very thin, so to zPosition raise a pixel can let the green view front, of course 0.1 or 0.0001 can also do, but it is best not to do so, because floating-point type rounding calculation may cause some inconvenience.

Listing 3.3

@interface Viewcontroller () @property (nonatomic, weak) Iboutlet UIView *greenview; @property (nonatomic, weak) Iboutlet U IView *redview; @end @implementation viewcontroller-(void) viewdidload{    [Super Viewdidload];    ?    Move the green view zposition nearer to the camera    self.greenView.layer.zPosition = 1.0f;} @end

Figure 3.9 The Green view is drawn in front of the red view

Hit testing

The first chapter, "Layer tree," confirms the best use of layer-dependent views rather than creating separate layer relationships. One reason is to handle the extra complex touch events.

CALayerDoes not care about any response chain events, so you cannot directly handle touch events or gestures. But it has a series of ways to help you deal with events: -containsPoint: and -hitTest: .

-containsPoint:Accept one in the coordinate system of this layer CGPoint , if this point is frame returned within the range of the layer YES . Another appropriate version of the project in the first chapter, shown in Listing 3.4, is the use of the -containsPoint: method to determine whether the layer that is white or blue is touched (Figure 3.10). This requires that the touch coordinates be converted to coordinates under each layer's coordinate system, and the results are inconvenient.

Listing 3.4 using Containspoint to determine which layer is clicked

@interface Viewcontroller () @property (nonatomic, weak) Iboutlet UIView *layerview; @property (nonatomic, weak) Calayer *b    Luelayer; @end @implementation viewcontroller-(void) viewdidload{[Super Viewdidload];    Create Sublayer self.bluelayer = [Calayer layer];    Self.blueLayer.frame = CGRectMake (50.0f, 50.0f, 100.0f, 100.0f); Self.blueLayer.backgroundColor = [Uicolor Bluecolor].    Cgcolor; Add it to our view [Self.layerView.layer AddSublayer:self.blueLayer];}  -(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//get touch Position relative to main view Cgpoint    Point = [[touches anyobject] locationInView:self.view]; Convert point to the white layer's coordinates point = [Self.layerView.layer convertpoint:point fromlayer:self.view.l    Ayer]; Get layer using containspoint:if ([Self.layerView.layer containspoint:point]) {//convert point to Bluelayer ' s coordinates point = [Self.bluelayer convertpoint:point fromLayer:self.layerViEw.layer];                                         if ([Self.bluelayer Containspoint:point]) {[[[Uialertview alloc] initwithtitle:@ "Inside Blue Layer"                               Message:nil Delegate:nil        cancelbuttontitle:@ "OK" otherbuttontitles:nil] show]; } else {[[[Uialertview alloc] initwithtitle:@ "Inside white Layer" Messa                              Ge:nil delegate:nil cancelbuttontitle:@ "OK"        Otherbuttontitles:nil] "show"; }}} @end

Figure 3.1 Click Layer is correctly identified

-hitTest:The method also accepts a CGPoint type parameter, not a BOOL type, which returns the layer itself, or the leaf node layer that contains the coordinate point. This means that it is no longer necessary to -containsPoint: manually transform or test the coordinates of a click in each sublayer, as used. If this point is outside the extent of the outermost layer, nil is returned. -hitTest:the code for the specific use of the clicked layer is shown in Listing 3.5.

Listing 3.5 using HitTest to determine which layer is clicked

-(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//get Touch    Position Cgpoint point = [[touches anyobject] locationInView:self.view];    Get touched layer Calayer *layer = [Self.layerView.layer hittest:point]; Get layer using hitTest if (layer = = Self.bluelayer) {[[[Uialertview alloc] initwithtitle:@ "Inside Blue layer "Message:nil Delegate:nil C    ancelbuttontitle:@ "OK" otherbuttontitles:nil] show];                                    } else if (layer = = Self.layerView.layer) {[[[Uialertview alloc] initwithtitle:@ "Inside white layer" Message:nil Delegate:nil Cancelbuttontitl    e:@ "OK" otherbuttontitles:nil] show]; }}

Note When you call a layer's -hitTest: methods, the order of the measurements is strictly dependent on the layer order in the layer tree (similar to UIView processing events). 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. We will discuss this issue in detail in the fifth chapter.

Automatic layout

You may have used UIViewAutoresizingMask some of the types of constants that are applied when the parent view changes size, as well as the UIView frame updated scene (usually used for the portrait-to-landscape toggle).

In IOS6, Apple introduced the automatic typesetting mechanism, which differs from auto-tuning and is more complex.

On the Mac OS platform, CALayer there is a layoutManager mechanism called attributes that can be implemented by CALayoutManager protocols and CAConstraintLayoutManager classes to automate typesetting. But for some reason, this does not apply on iOS.

When using a view, you can take advantage of the UIView exposed and API of the class interface, UIViewAutoresizingMask NSLayoutConstraint but if you want to control CALayer the layout, you need to do it manually. The simplest way is to use the CALayerDelegate following function:

-(void) Layoutsublayersoflayer: (Calayer *) layer;

This function will be executed when the layer is bounds changed, or when the layer's -setNeedsLayout method is called. This allows you to manually rearrange or readjust the size of the sublayers, but not the same as UIView the autoresizingMask properties of the constraints adaptive screen rotation.

This is one of the other important reasons why it is best to use views instead of separate layers to build applications.

Summarize

This chapter covers the CALayer collection structure, including its frame , position and bounds , describes the concept of layers within a three-dimensional space, and how to respond to events within a separate layer, and finally illustrates the lack of Core animation support for auto-tuning and auto-layout on the iOS platform.

In the fourth chapter, "Visual effects," we go on to introduce some features of the layer's appearance.

[IOS animation]-calayer layer geometry

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.