IOS Core Animation Advanced techniques-Timer-based animations

Source: Internet
Author: User
Tags strcmp

On 10 chapters:

    1. Layer Tree
    2. Layer's Homestay Map
    3. Layer geometry
    4. Layer Visual effects
    5. Layer transformations
    6. Dedicated layers
    7. Implicit animations
    8. An explicit animation
    9. Layer Time
    10. Layer buffering

This essay mainly introduces the timer-based animations.

Timed Frames:

    • Demonstration Example://using Nstimer to achieve elastic ball animation
//Add ball Image ViewUIImage *ballimage = [UIImage imagenamed:@"Ball.png"];self.ballview=[[Uiimageview alloc] initwithimage:ballimage]; [Self.containerview AddSubview:self.ballView];//AnimatefloatInterpolatefloatFromfloatTo,floatTime ) {return(to-from) * time +from ;}floatBounceeaseout (floatt) {if(T <4/11.0) {return(121* t/t)/16.0;} Else if(T <8/11.0) {return(363/40.0* t)-( About/10.0* t) + -/5.0;} Else if(T <9/10.0) {return(4356/361.0* t)-(35442/1805.0* t) +16061/1805.0;}return( Wu/5.0* t)-(513/25.0* t) +268/25.0;}- (ID) Interpolatefromvalue: (ID) Fromvalue Tovalue: (ID) Tovalue Time: (float) time{if([Fromvalue Iskindofclass:[nsvalueclass]]) {//Get TypeConst Char*type = [(Nsvalue *) Fromvalue Objctype];if(strcmp (Type, @encode (cgpoint)) = =0) {Cgpoint from=[Fromvalue Cgpointvalue]; Cgpoint to=[Tovalue Cgpointvalue]; Cgpoint result=Cgpointmake (interpolate (from.x, to.x, Time), Interpolate (From.y, TO.Y, Time));return[Nsvalue Valuewithcgpoint:result];}}//provide safe default implementationreturn(Time <0.5)?Fromvalue:tovalue;}- (void) animate{//reset ball to top of screenSelf.ballView.center = Cgpointmake ( Max, +);//Configure the animationSelf.duration =1.0; Self.timeoffset=0.0; Self.fromvalue= [Nsvalue Valuewithcgpoint:cgpointmake ( Max, +)];self.tovalue= [Nsvalue Valuewithcgpoint:cgpointmake ( Max,268)];//Stop the timer if it ' s already running[Self.timer invalidate];//Start the timerSelf.timer = [Nstimer scheduledtimerwithtimeinterval:1/60.0target:selfselector: @selector (step:) UserInfo:nilrepeats:YES];}- (void) Step: (Nstimer *) step{//Update Time offsetSelf.timeoffset = MIN (Self.timeoffset +1/60.0, self.duration);//Get normalized time offset (in range 0-1)floatTime = Self.timeoffset/self.duration;//Apply easingTime =bounceeaseout (time);//interpolate PositionIDPosition =[self interpolateFromValue:self.fromValuetoValue:self.toValuetime:time];//move ball view to new positionSelf.ballView.center =[position cgpointvalue];//Stop the timer if we ' ve reached the end of the animationif(Self.timeoffset >=self.duration) {[Self.timer Invalidate];self.timer=Nil;}}
    • /*
    • If you want to animate a lot of things on the screen at once, there's obviously a lot of problems.
    • Nstimer is not the best solution, in order to understand this, we need to know exactly how Nstimer works.
    • */

Nstimer Working principle:

    • Each thread on iOS manages a nsrunloop with a loop to complete a list of tasks
    • For the main thread, these tasks include the following:
      • 1. Handling Touch Events
      • 2. Sending and receiving network packets
      • 3. Execute code that uses GCD
      • 4. Handling Timer behavior
      • 5. Screen Redraw
    • When a nstimer is set, it is inserted into the current task list and is not executed until the specified time has elapsed (after his last task has been completed), which usually results in a delay of several milliseconds, depending on how long it takes to end a task.
    • There is no guarantee that the timer will be executed 60 times exactly one second and can be optimized by some means:

1. Use Cadisplaylink to keep the update frequency tightly controlled after each screen refresh

2. Animate based on the duration of the actual frame rather than the assumed update frequency

3. Adjust the run loop mode of the animation timer so that it is not disturbed by other events

      • 1.CADisplayLink:
        • Another class similar to nstimer provided by coreanimation
        • It always starts before the screen finishes an update
        • There is an integer Frameinterval property that specifies how many frames are spaced before execution. The default value is 1, which means that every time the screen is updated, it is executed once
        • If the animation's code executes for more than one-sixtieth seconds, you can specify Frameinterval as 2, which means that the animation executes once every other frame (30 frames per second) or 3, that is, 20 times a second, and so on.
      • 2. Calculate the duration of the frame:
        • The current time is recorded with Cacurrentmediatime () at the start of each frame, and then compared to the time recorded in the previous frame.
        • By comparing these times, we can get the true duration of each frame, and then replace the hard-coded one-sixtieth seconds
        • Example://To make the animation smoother by measuring the duration of no frames
          • Add Ball Image View
          • UIImage *ballimage = [UIImage imagenamed:@ "Ball.png"];
          • Self.ballview = [[Uiimageview alloc] initwithimage:ballimage];
          • [Self.containerview AddSubview:self.ballView];
          • Animate
          • Float interpolate (float from, float to, float time) {
          • Return (to-from) * time + from;
          • }
          • float bounceeaseout (float t) {
          • if (T < 4/11.0) {
          • return (121 * t * t)/16.0;
          • } else if (T < 8/11.0) {
          • return (363/40.0 * t * t)-(99/10.0 * t) + 17/5.0;
          • } else if (T < 9/10.0) {
          • return (4356/361.0 * t * t)-(35442/1805.0 * t) + 16061/1805.0;
          • }
          • return (54/5.0 * t * t)-(513/25.0 * t) + 268/25.0;
          • }
          • -(ID) Interpolatefromvalue: (ID) fromvalue tovalue: (ID) tovalue time: (float) time{
          • if ([Fromvalue Iskindofclass:[nsvalue class]]) {
          • Get type
          • const char *type = [(Nsvalue *) Fromvalue Objctype];
          • if (strcmp (Type, @encode (cgpoint)) = = 0) {
          • Cgpoint from = [Fromvalue cgpointvalue];
          • Cgpoint to = [Tovalue cgpointvalue];
          • Cgpoint result = Cgpointmake (Interpolate (from.x, to.x, Time), Interpolate (From.y, TO.Y, time));
          • return [Nsvalue Valuewithcgpoint:result];
          • }
          • }
          • Provide safe default implementation
          • Return (Time < 0.5)? Fromvalue:tovalue;
          • }
          • -(void) animate{
          • Reset ball to top of screen
          • Self.ballView.center = Cgpointmake (150, 32);
          • Configure the animation
          • Self.duration = 1.0;
          • Self.timeoffset = 0.0;
          • Self.fromvalue = [Nsvalue valuewithcgpoint:cgpointmake (150, 32)];
          • Self.tovalue = [Nsvalue valuewithcgpoint:cgpointmake (150, 268)];
          • Stop the timer if it ' s already running
          • [Self.timer invalidate];
          • Start the timer
          • Self.laststep = Cacurrentmediatime ();
          • Self.timer = [Cadisplaylink displaylinkwithtarget:self
          • Selector: @selector (step:)];
          • [Self.timer Addtorunloop:[nsrunloop Mainrunloop]
          • Formode:nsdefaultrunloopmode];
          • }
          • -(void) Step: (Cadisplaylink *) timer{
          • Calculate Time Delta
          • Cftimeinterval thisstep = Cacurrentmediatime ();
          • Cftimeinterval stepduration = Thisstep-self.laststep;
          • Self.laststep = Thisstep;
          • Update Time Offset
          • Self.timeoffset = MIN (Self.timeoffset + stepduration, self.duration);
          • Get normalized time offset (in range 0-1)
          • float time = self.timeoffset/self.duration;
          • Apply easing
          • Time = Bounceeaseout (time);
          • Interpolate position
          • ID position = [self interpolateFromValue:self.fromValue toValue:self.toValue
          • Time:time];
          • Move ball view to new position
          • Self.ballView.center = [position cgpointvalue];
          • Stop the timer If we ' ve reached the end of the animation
          • if (Self.timeoffset >= self.duration) {
          • [Self.timer invalidate];
          • Self.timer = nil;
          • }
          • }
      • 3.RunLoop mode:
        • When creating cadisplaylink, we need to specify a run loop and run loop mode, using the main thread of the run loop
        • Because any updates to the user interface need to be performed on the main thread
        • Some of the common run loop modes are:
          1. Nsdefaultrunloopmode-Standard Priority
          2. Nsrunloopcommonmodes-High priority
          3. Uitrackingrunloopmode-Animations for Uiscrollview and other controls
        • Specify multiple run loop modes for Cadisplaylink, so we can add both Nsdefaultrunloopmode and uitrackingrunloopmode to ensure that it is not interrupted by a slide, It is also not affected by other uikit control animations, like this:
          • Self.timer = [Cadisplaylink displaylinkwithtarget:self selector: @selector (step:)];
          • [Self.timer Addtorunloop:[nsrunloop Mainrunloop] formode:nsdefaultrunloopmode];
          • [Self.timer Addtorunloop:[nsrunloop Mainrunloop] formode:uitrackingrunloopmode];
        • Similar to Cadisplaylink, Nstimer can also be configured with different run loop modes, through other functions instead of +scheduledtimerwithtimeinterval: constructors:
          • Self.timer = [Nstimer timerwithtimeinterval:1/60.0
          • Target:self
          • Selector: @selector (step:)
          • Userinfo:nil
          • Repeats:yes];
          • [[Nsrunloop Mainrunloop] AddTimer:self.timer formode:nsrunloopcommonmodes];
  • Physical simulations:
    • iOS has its own physical engine uidynamic.

IOS Core Animation Advanced techniques-Timer-based animations

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.