在 onTouchEvent 中對 ImageView 先 setX/setY 移動位置,再啟動 ScaleAnimation,導致縮放中心點不固定,動畫效果異常。
ScaleAnimation 的縮放中心點由構造函數參數(RELATIVE_TO_SELF, 0.5f)決定,但若在動畫前改變 View 的 X/Y,View 的幾何中心相對父容器發生變化,導致視覺中心偏移。
ValueAnimator animator = ValueAnimator.ofFloat(1f, 0.5f);
animator.addUpdateListener(animation -> {
float scale = (float) animation.getAnimatedValue();
view.setScaleX(scale);
view.setScaleY(scale);
});
animator.setDuration(500);
animator.setRepeatCount(1);
animator.setRepeatMode(ValueAnimator.REVERSE);
// onTouch 中
view.setPivotX(view.getWidth() / 2f);
view.setPivotY(view.getHeight() / 2f);
view.setX(event.getX() - view.getWidth() / 2);
view.setY(event.getY() - view.getHeight() / 2);
animator.start();
setPivotX/Y 固定縮放中心為 View 自身中心。ValueAnimator 直接操作 scaleX/scaleY,不依賴佈局傳遞,效果更可控。