核心动画代码如下:
private ObjectAnimator alphaAnim, translateAnim, scaleAnim, rotateAnim; // 声明四个属性动画对象
private void initObjectAnim() {
// 构造一个在透明度上变化的属性动画
alphaAnim = ObjectAnimator.ofFloat(imageView, "alpha", 1f, 0.1f, 1f);
// 构造一个在横轴上平移的属性动画
translateAnim = ObjectAnimator.ofFloat(imageView, "translationX", 0f, -200f, 0f, 200f, 0f);
// 构造一个在纵轴上缩放的属性动画
scaleAnim = ObjectAnimator.ofFloat(imageView, "scaleY", 1f, 0.5f, 1f);
// 构造一个围绕中心点旋转的属性动画
rotateAnim = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f, 0f);
}
效果控制如下:
private String[] objectArray = {"灰度动画", "平移动画", "缩放动画", "旋转动画", "裁剪动画"};
// 播放指定类型的属性动画
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void playObjectAnim(int type) {
ObjectAnimator anim = null;
if (type == 0) { // 灰度动画
anim = alphaAnim;
} else if (type == 1) { // 平移动画
anim = translateAnim;
} else if (type == 2) { // 缩放动画
anim = scaleAnim;
} else if (type == 3) { // 旋转动画
anim = rotateAnim;
} else if (type == 4) { // 裁剪动画
int width = imageView.getWidth();
int height = imageView.getHeight();
// 构造一个从四周向中间裁剪的属性动画
ObjectAnimator clipAnim = ObjectAnimator.ofObject(imageView, "clipBounds",
new RectEvaluator(), new Rect(0, 0, width, height),
new Rect(width / 3, height / 3, width / 3 * 2, height / 3 * 2),
new Rect(0, 0, width, height));
anim = clipAnim;
}
if (anim != null) {
anim.setDuration(3000); // 设置动画的播放时长
anim.start(); // 开始播放属性动画
}
}
补充xml布局:
在最初的android动画框架里有许多的缺陷,后来随着android系统版本的迭代陆陆续续修复了。这些动画框架可能都用不到了。但参考学习还是不错的。