如何将包含平移的RotateAnimation动画改为ObjectAnimator实现
ObjectAnimator实现对等RotateAnimation效果的修正方案
你当前的实现存在两个核心逻辑偏差,按以下方式调整即可:
- 错误将固定平移逻辑放入动画属性:原实现中translationX、translationY是初始化时直接赋值的静态值,不需要随动画过程变化,你将其写入
PropertyValuesHolder会导致动画运行时平移量反复变动,和原效果不符。 - 未配置旋转支点:原
RotateAnimation传入了相对自身的自定义旋转支点,ObjectAnimator的rotation属性依赖视图自身的pivotX、pivotY参数确定旋转中心,你未配置这两个参数会导致旋转中心点错误。
修正后代码
var i = 0 for (image in imageList) { // 和原逻辑一致,先设置固定平移量 image.translationX = translationsize[i].x // 注意原代码此处translationY赋值用了translationsize[i].x,若为笔误可自行修改为translationsize[i].y image.translationY = translationsize[i].x // 配置旋转支点:原RotateAnimation的RELATIVE_TO_SELF参数为比例值,需乘视图宽高换算为实际像素坐标 image.pivotX = pivots[i].x * image.width image.pivotY = pivots[i].y * image.height // 仅构造旋转动画即可 val animator = ObjectAnimator.ofFloat(image, "rotation", 0f, 360f) animator.duration = 1500 animator.repeatCount = ObjectAnimator.INFINITE animator.repeatMode = ObjectAnimator.RESTART animator.interpolator = LinearInterpolator() animator.start() i++ }
额外说明
如果你确实需要将平移也做成随动画变化的效果,再将对应的PropertyValuesHolder添加到ObjectAnimator中即可,常规场景下和原RotateAnimation对等的效果不需要添加平移动画属性。
内容的提问来源于stack exchange,提问作者Christine
相关产品推荐
相关产品推荐

