You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何缩小ImageView(修改Bounds)并向下移动?现有代码存在上缩问题

解决ImageView向下移动至中心并缩小消失的问题

你现在遇到的问题是当前Transition动画会向上缩小,且缩放和移动是先后执行的,不符合你想要的「边向下移动到中心边缩小消失」的效果。我帮你分析下问题根源,再给出两种可行的解决方案:

问题根源

你当前设置了TransitionSet.ORDERING_SEQUENTIAL,这会让ChangeImageTransform(缩放动画)和ChangeBounds(位置变化动画)先后执行;再加上ImageView默认的缩放锚点是左上角,所以缩小的时候会往左上角收缩,看起来就是向上缩的效果。

解决方案一:用ObjectAnimator组合动画(更灵活)

这种方式能精准控制缩放、移动和透明度,完美实现边移动边缩小最后消失的效果:

// 获取屏幕中心的Y坐标(你也可以改成更靠下的目标位置)
int screenHeight = getResources().getDisplayMetrics().heightPixels;
float targetCenterY = screenHeight / 2f;
// 获取ImageView当前的Y位置
float currentY = imageView.getY();

// *关键!* 设置缩放锚点为ImageView自身中心,避免缩放时往左上角收缩
imageView.setPivotX(imageView.getWidth() / 2f);
imageView.setPivotY(imageView.getHeight() / 2f);

// 创建缩放动画:从原大小缩至完全消失
ObjectAnimator scaleXAnim = ObjectAnimator.ofFloat(imageView, View.SCALE_X, 1f, 0f);
ObjectAnimator scaleYAnim = ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 1f, 0f);

// 创建位移动画:从当前位置移动到屏幕中心Y坐标
float translateYDistance = targetCenterY - currentY;
ObjectAnimator translateYAnim = ObjectAnimator.ofFloat(imageView, View.TRANSLATION_Y, 0f, translateYDistance);

// 可选:添加透明度动画,让消失效果更自然
ObjectAnimator alphaAnim = ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f, 0f);

// 组合所有动画,同时执行,时长1000ms
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(scaleXAnim, scaleYAnim, translateYAnim, alphaAnim);
animatorSet.setDuration(1000);
animatorSet.start();

解决方案二:调整TransitionSet的配置

如果你想沿用原本的Transition框架,只需修改动画顺序和锚点,同时设置目标位置即可:

// *关键!* 设置缩放锚点为ImageView自身中心
imageView.setPivotX(imageView.getWidth() / 2f);
imageView.setPivotY(imageView.getHeight() / 2f);

// 计算目标布局位置(屏幕中心)
ViewGroup parentView = (ViewGroup) imageView.getParent();
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int screenHeight = getResources().getDisplayMetrics().heightPixels;
ViewGroup.LayoutParams params = imageView.getLayoutParams();
// 调整margin让ImageView移动到屏幕中心
params.width = imageView.getWidth();
params.height = imageView.getHeight();
params.leftMargin = (screenWidth - imageView.getWidth()) / 2;
params.topMargin = (screenHeight - imageView.getHeight()) / 2; // 想要更靠下可修改此值

// 创建过渡动画
ChangeImageTransform imageTransform = new ChangeImageTransform();
ChangeBounds changeBounds = new ChangeBounds();

TransitionSet set = new TransitionSet();
// 改为同时执行,让缩放和移动同步进行
set.setOrdering(TransitionSet.ORDERING_TOGETHER);
set.addTransition(imageTransform);
set.addTransition(changeBounds);
set.setDuration(1000);

// 启动过渡动画
TransitionManager.beginDelayedTransition(parentView, set);
// 应用目标布局参数和缩放值
imageView.setLayoutParams(params);
imageView.setScaleX(0f);
imageView.setScaleY(0f);

两种方案都能实现你要的效果,第一种更灵活,适合自定义复杂动画;第二种贴合你原本的代码逻辑,改动更小。

内容的提问来源于stack exchange,提问作者blackHawk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:02:39