IPhone/IOS core animation Development Summary (calayer)

Source: Internet
Author: User
Document directory
  • Vi. subclasses of calayer
1. Important Parameters

Bounds, frame, and position are basic geometric positioning. numerical changes affect each other.

Anchorpoint: the Unit parameter (0-1) indicates the conversion source point during deformation (transform ).

Zposition: equivalent to the concept of Z-index in CSS. Apple suggests not to use this to replace the calayer hierarchy settings.

Cornerradius: rounded corner

2. ry (transforming a layer's geometry)

1. Use catransform3d series methods

// Convert cgaffinetransform to catransform3d layer=1.transform = transform (cost (1,-1); // The catransform3d series method layer=1.transform = catransform3dmakescale (-1, 1, 1 ); layer1_1.transform = catransform3dscale (catransform3dmakescale (-2, 1, 1),-1, 1, 1); layer1_1.transform = catransform3didentity;

2. Modify the data structure of catransform3d

Catransform3d trans = catransform3didentity; nslog (@ "% F", trans. m44); // It cannot be 1 divided by. It must be 1.0 divided by 1000 (zdistance) // wrong trans. M 34 = 1/100. 00 trans. m34 =-1.0/1000; Trans = catransform3dtranslate (trans, 0, 0,-240); Trans = catransform3drotate (trans, D2R (90), 1, 0, 0 ); trans = catransform3dtranslate (trans, 0, 0,240); [layer1 settransform: Trans];

3. Set key paths (rotation, scale, translation) for key-valre)

        [layer1 setValue:[NSNumber numberWithInt:200] forKeyPath:@"transform.translation.x"];

3. layer Layer Structure (layer-tree hierarchy)

1. Add, insert, remove, and replace for Tree Structure Construction

2. Reset (reposition and resizing) Layer

A) You can adjust the size by modifying the parameters mentioned at the first point.

B) when the needsdisplayonboundschange is set to yes, setneedsdisplay is automatically called when the bounds change, the display method of the layer is called, or setneedsdisplay is directly displayed (setneedsdisplayinrect cannot be used ), the display method of the custom layer is also called. Or setneeslayout, which calls the layoutsublayers of the layer. (PS: The layoutmanager and autoresizingmask methods cannot be used. This is Mac
On the OS .)

C) Implement the custom Layout Method in layoutsubviews of uiview.

3. If maskstobounds is set to yes, sublayers is cropped. Otherwise, no cropping is required. sublayers can exceed the bounds of the superlayer.

4. Action

Triggered when you change the parameters of a layer or add, delete, hide, or replace a layer.

The trigger method can be subclass calayer,-(ID <caaction>) actionforkey :( nsstring *) Key; proxy method-(ID <caaction>) actionforlayer :( calayer *) forkey :( nsstring *) Key

-(ID <caaction>) actionforlayer :( calayer *) layer forkey :( nsstring *) event {catransition * anim = nil; If ([event isequaltostring: @ "contents"]) {anim = [catransition animation]; anim. duration = 2; anim. timingfunction = [camediatimingfunction functionwithname: kcamediatimingfunctioneaseineaseout]; anim. type = @ "cube"; anim. subtype = kcatransitionfromright;} return anim; // do not execute any animation // return nil ;}

The apple documentation provides a method to modify the default animation of sublayers.

        NSMutableDictionary *cActions=[NSMutableDictionary dictionaryWithDictionary:[layer1_1 actions]];        [cActions setObject:[NSNull null] forKey:@"sublayers"];        layer1_1.actions=cActions;

Implement caaction Protocol

Implementation Method runactionforkey: object: arguments in the proxy class

-(void)runActionForKey:(NSString *)event object:(id)anObject arguments:(NSDictionary *)dict{        NSLog(@"runActionForKey:\"%@\" object:%@ arguments:%@", event, anObject, dict);        CATransition *anim=nil;        if([event isEqualToString:@"test"]){                anim=[CATransition animation];                anim.duration=2;                anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];                anim.type=@"cube";                anim.subtype=kCATransitionFromRight;        }        [(CALayer*)anObject addAnimation:anim forKey:@"contets"];}

Trigger runactionforkey

// Add a custom action and the agent of the corresponding Triggering Method. You can define an animation subclass (caanimation) layer1.actions = [nsdictionary dictionarywithobjectsandkeys: [[fclayerdelegate alloc] init], @ "test", nil]; // actually triggered. When the test parameter is set, the final trigger is the cube rotation in runactionforkey [layer1 setvalue: [nsnumber numberwithint: 19] forkey: @ "test"];

4. Provide layer content (providing layer content)

1. Set the contents attribute cgimageref

   layer1.contents=(id)image1.CGImage;

2. Use delegate to provide content

A) displaylayer :( calayer *)

B)-(void) drawlayer :( calayer *) incontext :( cgcontextref)

// Declare the proxy @ interface fclayerdeledegate: nsobject @ end // implement the proxy @ implementation fclayerdelegate // overwrite this method, and the subsequent method will not be executed. either of the two takes one of them, determine the next operation based on the input value-(void) displaylayer :( calayer *) layer {nslog (@ "% @", [layer valueforkey: @ "test"]);} -(void) drawlayer :( calayer *) ly incontext :( cgcontextref) Context {cgcontextsetfillcolorwithcolor (context, [uicolor redcolor] cgcolor]); cgcontextfillrect (context, Ly. bounds);} @ end
// Run the code calayer * layer1_3 = [calayer layer]; layer1_3.delegate = [[fclayerdelegate alloc] init]; [layer1_3 setvalue: @ "teststring" forkey: @ "test"]; [layer1_3 setneedsdisplay];

PS: The preceding method is used for calayer itself (not its own subclass)

3) provide content using subclass

A) display

B) drawincontext :( cgcontextref)

Similar to the previous proxy mode, only the layer parameter is missing because the layer itself (Self );

4) content Layout

By default, content images will be paved with bounds full of the entire layer. To make contents display in the layer according to the original size, you must set contentsgravity.

Roughly two parameters

1. Location Parameter. Note that the IOS coordinate is Y, so bottom is top

2. Set the fill mode.

layer1_3.contentsGravity=kCAGravityBottomLeft;layer1_3.contents=(id)image3.CGImage;//layer1_3.contentsGravity=kCAGravityResizeAspectFill;

PS: In addition, The contentscenter attribute can specify the stretch area under the parameter of the full mode. It is pointed out that the stretch range is specified, but it does not seem to work. Temporarily ignore.

5. Animation

1. animated Clusters

A) Main Parameters of camediatiming Protocol

Speed: execution speed. If the speed is 2, a 10-second duration takes only 5 seconds. The subclass parameter is relative to the parent class parameter. If the subclass is 2 and the parent class is 2, it takes 2.5 seconds to complete

Repeatcount | repeatduration: the number of repetitions and the interval between duplicates. If repeatcount is set to 1e100f, The repeatcount is infinite.

Fillmode: determines the animation end state. It is valid only when it is set together with the removeoncompletion parameter. The status after the animation ends does not affect the position of the layer. In fact, the layer remains unchanged.

In addition, there are duration, autoreverses, begintime, timeoffset

B) caanimation

Timingfunction: Specifies a camediatimingfunction. There are two ways to provide it. One is a constant such as kcamediatimingfunctionlinear, and the other is to customize two control points to customize a time curve.

Functionwithcontrolpoints ::::.

Delegate: two proxy methods, animationdidstart: And animationdidstop: Finished:

2. Normal Animation

Any calayer's animated attributes or CTM changes are animated transitions. This is called implicit animation. I will not introduce it here

This section mainly introduces the explicit animation.

A) cabasicanimation changes the settings of a certain attribute.

        CABasicAnimation *anim;        anim=[CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];        anim.duration=8;        anim.autoreverses=NO;        anim.repeatCount=2;        anim.fromValue=[NSNumber numberWithFloat:d2r(0)];        anim.toValue=[NSNumber numberWithFloat:d2r(-90)];        //  layer1.transform=CATransform3DTranslate(CATransform3DIdentity, 0, 0, 100);        [layer1 addAnimation:anim forKey:@"layer1Rotation"];

B) cakeyframeanimation

Two key frame methods are available:

Parameter path, create cgpathref

Path: cgpathref is generally used to move complex locations, for example:

Cgmutablepathref Path = cgpathcreatemutable (); cgpathmovetopoint (path, null, 40,420); cgpathaddcurvetopoint (path, null, 40, 40,160, 40,160,420); cgpathaddcurvetopoint (path, null, 160, 40,280, 40,280,420); cakeyframeanimation * anim = [cakeyframeanimation animationwithkeypath: @ "position"]; anim. path = path; anim. duration = 3; // whether the image rotates anim during movement. rotationmode = kcaanimationrotateauto; // The animation State at the end of the animation, where the animation stops at anim. removedoncompletion = no; anim. fillmode = kcafillmodeforwards; // set the keytimes path to add two vertices, so the duration is set to 2 segments. The first segment is faster than 3/10, And the last segment is slower than 7/10 anim. calculationmode = kcaanimationlinear; anim. keytimes = [nsarray flood: [nsnumber numberwithfloat: 0.0], [nsnumber numberwithfloat: 0.3], [nsnumber numberwithfloat: 1.0], nil]; [layer1 addanimation: anim forkey: @ "nm1"]; cgpathrelease (PATH );

Parameter Values: array of Objects

If objects is cgimage and key-path is "contents", it is image switching.

        CAKeyframeAnimation *anim=[CAKeyframeAnimation animationWithKeyPath:@"contents"];        anim.duration=3;        anim.values=[NSArray arrayWithObjects:(id)image1.CGImage,(id)image2.CGImage,(id)image3.CGImage,nil];        [layer1 addAnimation:anim forKey:@"nm2"];

If the objects is catransform3d and the key-path is "transform", it is the transformation coordinate.

        CAKeyframeAnimation *anim2=[CAKeyframeAnimation animationWithKeyPath:@"transform"];        anim2.duration=3;        anim2.repeatCount=1000;        anim2.autoreverses=YES;        CATransform3D trans=CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1);        CATransform3D trans2=CATransform3DScale(CATransform3DIdentity, 1, 1, 1);        anim2.values=[NSArray arrayWithObjects:[NSValue valueWithCATransform3D:trans],[NSValue valueWithCATransform3D:trans2],nil];        [layer1 addAnimation:anim2 forKey:@"nm3"];

If you set both, you can also see the animation effect at the same time. For example, you can see the effects of switching between images and enlarging or downgrading them.
Do not set keyframe animation for parameters such as frame and size. It does not seem to have any effect. Position is acceptable.

3. Transaction)

        [CATransaction begin];        [CATransaction setValue:[NSNumber numberWithFloat:.5f] forKey:kCATransactionAnimationDuration];        layer1.position=CGPointMake(0, 0);        layer1.opacity=0;        [CATransaction commit];

You can modify the Time of the implicit animation through a transaction, otherwise there is no way to modify it.

4. animation transition)

// Catransition * animation = [catransition animation]; animation. delegate = self; animation. duration = 2; animation. timingfunction = uiviewanimationcurveeaseinout; // animation. type = kcatransitionfade; animation. type = @ "cube"; animation. subtype = kcatransitionfromleft; // two views exchange nsuinteger Green = [[self. view subviews] indexofobject: Self. greenview]; nsuinteger Blue = [[self. view subviews] indexofobject: Self. blueview]; [self. view exchangesubviewatindex: Green withsubviewatindex: BLue]; [layer1 addanimation: animation forkey: @ "Animation"];

There is a difference between the transition of view and the transition of layer. There is an example of transition on the Internet that contains a total of 12 transformations, which is quite useful. In addition, you can set startprogress and endprogress so that the animation can be executed to a specific position. For example, if pagecurup is used, the animation can be halved, which is cool!

Vi. subclasses of calayer

With the update of IOS 5.0, calayer has added new members. I have studied some of them a little. Now I will summarize some of them, some of which are new, and some are earlier than 5.0.

1. careplicatorlayer

As the name suggests, this class is used to create repeated layers, and you can perform a gradient Based on the set parameters.

// Set calayer * layer1 = [calayer layer]; layer1.position = cgpointmake (10,200); layer1.bounds = cgrectmake (0, 0, 20, 20) for Small layers of each unit ); gradient = [[uicolor yellowcolor] cgcolor]; layer1.cornerradius = 2; gradient = [[uicolor blackcolor] cgcolor]; layer1.shadowradius = 4.0f; layer1.shadowoffset = cgsizemake (0.0f, 3.0f); gradient =. 8; layer1.opacity = 0.8; layer1.bordercolor = [[uicolor whitecolor] cgcolor]; layer1.borderwidth = 2.0; // set the parent container careplicatorlayer * xlayer = [careplicatorlayer]; xlayer. instancecount = 11; // how many word elements are generated xlayer. instancedelay =. 2; // delay in generating xlayer. instancegreenoffset = -. 03; // green offset xlayer. instanceredoffset = -. 02; // red offset xlayer. instanceblueoffset = -. 01; // The Blue offset xlayer. instancealphaoffset = -. 05; xlayer. instancetransform = catransform3dmaketranslation (25, 0,200); // element displacement offset [xlayer addsublayer: layer1]; // Add an element to xlayer. preservesdepth = yes; // whether the superlayer enables 3D depth of field computing // sets the depth of field catransform3d transform = catransform3didentity; transform. m34 =-1/20000000f; xlayer. transform = transform;

You can even add a composite animation to the layer so that each element can be animated in sequence. The main method is as follows:

This is the instancetransform for the layer, which can affect the movement of the same animation for each cell. below is the animation for translation.

- (CABasicAnimation *)pushAnimation {    CABasicAnimation *pushAnim =    [CABasicAnimation animationWithKeyPath:@"instanceTransform"];    pushAnim.fromValue =[NSValue valueWithCATransform3D:CATransform3DMakeTranslation(SUBLAYER_WIDTH+INTERSPACE, 0, 0)];    pushAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(SUBLAYER_WIDTH+INTERSPACE+60, 0, 0)];    pushAnim.duration = 3.0;    pushAnim.autoreverses = YES;    pushAnim.repeatCount = HUGE_VAL;    pushAnim.timingFunction =    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];    return pushAnim;}

2. caemitterlayer & caemittercell

There are a lot of particle-related code on the Internet, such as snowflake floating, burning flame, and smoke effect, which are actually implemented through the settings of this class. The usage is similar to that of careplicatorlayer. This article mainly introduces the following parameters.

// Configure the particle emitter to the top edge of the screencaemitterlayer * snowemitter = [caemitterlayer layer]; snowemitter. emitterposition = cgpointmake (self. view. bounds. size. width/2.0,-30); // sets the launch position, which is related to snowemitter in emittermode. emitterzposition = 50; // The Position of the launch point Z, which is related to the emittermode snowemitter. emittersize = cgsizemake (self. view. bounds. size. width * 2.0, 0.0); // the range of the launch point, which is related to the emittermode snowemitter. emitterdepth = 100; // launch from the production environment // snowemitter. emittermode = kcaemitterlayeroutline; // snowemitter. emittershape = kcaemitterlayerline; // emits light from a cube. In this way, snow will have different sizes in 3D. emittermode = kcaemitterlayervolume; snowemitter. emittershape = kcaemitterlayercuboid; // set the transmitting unit caemittercell * snowflake = [caemittercell emittercell]; Snowflake. birthrate = 3.0; // one snowflake occurs every second. lifetime = 120.0; // The lifetime is 120 seconds. velocity = 20; // the initial speed of the snowflake. velocityrange = 10; // random range of initial speed Snowflake. yacceleration = 10; // y axis acceleration, of course, Z, X axis // Snowflake. emissionrange =-0.5 * m_pi; // specifies the range of the emission angle. This parameter seems to be directed only to the screen, that is, the negative axis snowflake of Z. spin = 0.0; Snowflake. spinrange =-0.25 * m_pi; // self-rotating range Snowflake. contents = (ID) [[uiimage imagenamed: @ "flake"] cgimage]; Snowflake. color = [[uicolor colorwithred: 0.600 Green: 0.658 Blue: 0.743 ALPHA: 1.000] cgcolor]; // make the flakes seem inset in the backgroundsnowemitter. shadowopacity = 1.0; snowemitter. shadowradius = 0.0; snowemitter. shadowoffset = cgsizemake (0.0, 1.0); snowemitter. shadowcolor = [[uicolor whitecolor] cgcolor]; // Snowflake. emissionlatitude =-m_pi_2; // rotate snowemitter according to the Z axis. preservesdepth = yes; catransform3d transform = catransform3didentity; transform. m34 =-1.0/300366f; self. view. layer. transform = transform; // Add everything to our backing layer below the uicontol defined in the storyboardsnowemitter. emittercells = [nsarray arraywithobject: snowflake]; [self. view. layer insertsublayer: snowemitter atindex: 0];

It is mainly used for applications with the 3DZ axis. The closer you are to your field of view, the larger the image is. This effect can be achieved by setting the depth of field of the parent layer.

Reference:

Animation types and timing programming guide

Core animation programming guide

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.