Android动画框架,让平移动画更添魅力

使用startAnimation()​方法时,View的位置在动画结束后会重置为原始位置,除非在动画结束时手动更新View的位置。

使用startAnimation()​方法时,View的位置在动画结束后会重置为原始位置,除非在动画结束时手动更新View的位置。

使用ObjectAnimator

ObjectAnimator是Android3.0引入的一个强大的动画框架,用于对任何对象的属性进行动画处理。可以使用ObjectAnimator来改变View的translationX和translationY属性来实现View的平移动画。

View view = findViewById(R.id.view);
ObjectAnimator animatorX = ObjectAnimator.ofFloat(view, "translationX", 0f, 100f); // 平移X轴
ObjectAnimator animatorY = ObjectAnimator.ofFloat(view, "translationY", 0f, 50f); // 平移Y轴

AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(animatorX).with(animatorY); // 同时执行X轴和Y轴动画
animatorSet.setDuration(1000); // 设置动画时长
animatorSet.start(); // 开始动画

使用ValueAnimator

ValueAnimator是一个更底层的动画框架,可以在动画过程中生成一系列的值,然后使用这些值来更新View的属性。对于平移动画,通过监听ValueAnimator的值变化更新View的translationX和translationY属性。

ValueAnimator animator = ValueAnimator.ofFloat(0f, 100f); // 生成0到100的值
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float value = (float) animation.getAnimatedValue();
        view.setTranslationX(value); // 更新View的X轴位置
    }
});
animator.setDuration(1000); 
animator.start();

使用ViewPropertyAnimator

从Android 3.0开始,View类提供了一个animate()方法,返回一个ViewPropertyAnimator对象,可以用来链式调用多个动画方法。

view.animate()
        .translationX(100f) // 平移X轴
        .translationY(50f) // 平移Y轴
        .setDuration(1000) // 设置动画时长
        .start(); // 开始动画

使用XML动画

可以在XML文件中定义动画,并在需要时加载并应用这些动画。

<!-- res/anim/translate_animation.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromXDelta="0%p"
        android:toXDelta="100%p"
        android:fromYDelta="0%p"
        android:toYDelta="50%p"
        android:duration="1000"/>
</set>
Animation animation = AnimationUtils.loadAnimation(this, R.anim.translate_animation);
view.startAnimation(animation);

注意:使用startAnimation()方法时,View的位置在动画结束后会重置为原始位置,除非在动画结束时手动更新View的位置。如果希望View在动画结束后保持在最终位置,可以考虑使用前面提到的ObjectAnimator、ValueAnimator或ViewPropertyAnimator方法。

使用drawBitmap

通过drawBitmap在不同的位置画出图片,适合图片作为平移动画的需求。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image);
int width = ScreenUtils.getScreenWidth() - bitmap.getWidth();
//int height = bitmap.getHeight();
//绘制原图
//canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.drawBitmap(bitmap, progress * width / 100, 0, null);
//平移图片
Matrix matrix = new Matrix();
matrix.postTranslate(progress * width / 100, height);
canvas.drawBitmap(bitmap, matrix, null);

©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经

(0)
打赏 微信扫码打赏 微信扫码打赏 支付宝扫码打赏 支付宝扫码打赏
清一色的头像清一色管理团队
上一篇 2024年6月5日 00:05
下一篇 2024年6月5日 00:06

相关推荐

发表评论

登录后才能评论

联系我们

在线咨询:1643011589-QQbutton

手机:13798586780

QQ/微信:1074760229

QQ群:551893940

工作时间:工作日9:00-18:00,节假日休息

关注微信