Back to Blog Home
← all posts

Using NativeScript animation APIs

August 21, 2015 — by Valio Stoychev

With our 1.3 release, coming in September, we are adding the highly requested Animations support in NativeScript. There will be a dedicated blog post ​explaining in-depth about our animations support. If you are impatient please read more info on the animations in the GitHub issue. If you are curious how the animations are implemented and you like to read TypeScript code - please see the implementation here.


In this blog post I will share a simple example, created by one of the senior developers in the team Alex, which was inspired by an animated GIF in a tweet:

So we decided to dogfood our own animations and to see how easy it will be implement this in NativeScript in a cross-platform way. It turned out to be quite easy - just a few lines of code.

You can see the entire source code here, but here is the most interesting part.

First we need to initialize the “circle” elements. In our case we are simple creating empty buttons and applying a simple CSS definition over them:

for (var i = 0; i < count; i++) {
    views[i] = new buttons.Button();
    views[i].cssClass = "circle";
    plot.addChild(views[i]);
}

Here is and the CSS definition:
.circle {
    width: 20;
    height: 20;
    border-radius: 10;
    border-width: 1;
    border-color: gray;
    background-color: aqua;    
}

Now when the elements are on the screen we should initialize the animation:

for (var i = 0; i < count; i++) {
    setTimeout(createStarter(i), delay * (i + 1));
}
 
function createStarter(idx) {
    return function () {
        animate(idx, 1);
    };
}

The animation code that actually performs this beautiful animations is here:

function animate(index, direction) {
    var v = views[index];
    var x = direction * Math.cos(piFract * index) * W;
    var y = direction * Math.sin(piFract * index) * H;
 
    v.animate({
        translate: { x: x, y: y },
        duration: duration,
        iterations: 1,
        curve: v.ios ? UIViewAnimationCurve.UIViewAnimationCurveEaseInOut : new android.view.animation.AccelerateDecelerateInterpolator()
    }).then(function () { animate(index, -direction); });
}

The animation variables are defined with the following constants:
var W = 150;
var H = 150;
var count = 8;
var duration = 4000;
var delay = (duration / count);
var piFract = Math.PI / count;

See the final result in this iOS emulator below:


Now the next step for you is to play with the shiny new animations API in NativeScript and send us any feedback!

For more examples like this please follow us on @NativeScript and star our NativeScript GitHub repository!