用javascript在码实云平台上,可以在云里编写原生的移动应用。移动应用的交互界面,添加动画效果,如果恰到好处,能够极大地提升用户体验。可以说,添加动画,是让用户尖叫的一个必要的元素。下面实例中,做了三个会动的按钮。
Class.create(Mash5.Widget, {
initialize : function (config, params) {
var container = Ti.UI.createView({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
backgroundColor : '#ddd'
});
this.setContentView(container);
var button1 = Ti.UI.createView({
bottom: dipToPx(-100),
width: '160dip',
height: '40dip',
backgroundColor : '#0d4',
borderRadius: dipToPx(20),
});
container.add(button1);
button1.add(Ti.UI.createLabel({
text: '我会动',
color: '#fff',
font: {fontSize : '20dip'},
}));
var button2 = Ti.UI.createView({
top: '100dip',
width: '160dip',
height: '40dip',
backgroundColor : '#d80',
borderRadius: dipToPx(20),
});
container.add(button2);
button2.add(Ti.UI.createLabel({
text: '我更会动',
color: '#fff',
font: {fontSize: '20dip'},
}));
var button3 = Ti.UI.createView({
width: '160dip',
height: '40dip',
backgroundColor : '#80d',
borderRadius: dipToPx(20),
});
container.add(button3);
button3.add(Ti.UI.createLabel({
text: '我会动3次',
color: '#fff',
font: {fontSize : '20dip'},
}));
// 添加动画效果
var a1 = Titanium.UI.createAnimation();
a1.duration = 500;
a1.bottom = dipToPx(100);
button1.animate(a1);
var matrix = Ti.UI.create2DMatrix();
button2.transform = matrix.translate(0, dipToPx(-300)).rotate(150);
button2.opacity = 0.3;
var a2 = Titanium.UI.createAnimation();
a2.duration = 1500;
a2.delay = 500;
a2.transform = matrix;
a2.opacity = 1;
button2.animate(a2);
var m3 = Ti.UI.create2DMatrix();
button3.transform = m3.translate(dipToPx(-200), dipToPx(-500)).rotate(150).scale(5, 5);
button3.opacity = 0;
var a3 = Titanium.UI.createAnimation();
a3.duration = 2000;
a3.delay = 2000;
a3.autoreverse = true;
a3.repeat = 3;
a3.transform = m3;
a3.opacity = 1;
button3.animate(a3);
}
})
这个实例给大家示意动画的编程方法。第一个按钮button1的动画最简单,是个针对bottom垂直平移的效果。事先用Titanium.UI.createAnimation准备好动画变量。这个变量设定好动画最终的结果数值,动画结束时会到达a1.bottom = dipToPx(100)。第二个按钮的动画效果丰富些,用了二维变换的矩阵Ti.UI.create2DMatrix。有了这个矩阵,可以方便地设定平移、旋转、缩放。通过button2.transform = matrix.translate(0, dipToPx(-300)).rotate(150),我们先把按钮2垂直向上移动300,然后转150度,动画从这个位置开始,恢复到按钮2的原始位置结束。第三个按钮的动画则综合了平移、旋转、放大三种变换,动画里用了回播和重复。