pivotX、pivotY 指定**變換(縮放、旋轉)的中心點坐標**,相對於 View 自身左上角 (0,0)。
float(像素)、percentage(自身寬高百分比)、percentageP(父容器寬高百分比)。50% 50%(View 幾何中心)。<scale
android:fromXScale="1.0" android:toXScale="0.5"
android:fromYScale="1.0" android:toYScale="0.5"
android:pivotX="50%" android:pivotY="50%"
android:duration="1000" />
<scale
android:pivotX="0%" android:pivotY="0%"
... />
<rotate
android:fromDegrees="0" android:toDegrees="360"
android:pivotX="50%" android:pivotY="100%"
... />
View view = findViewById(R.id.my_view);
// 設置為 View 寬度 25%、高度 75% 處
view.setPivotX(view.getWidth() * 0.25f);
view.setPivotY(view.getHeight() * 0.75f);
// 或使用屬性動畫
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.5f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.5f);
// pivot 必須在動畫開始前設置,動畫中改變無效
view.setPivotX(view.getWidth() / 2);
view.setPivotY(view.getHeight() / 2);
AnimatorSet set = new AnimatorSet();
set.playTogether(scaleX, scaleY);
set.start();
| 現象 | 原因 | 解決 |
|---|---|---|
| 動畫開始時 View 跳動 | pivot 設置在 onCreate,View 尚未布局,寬高為 0 | 在 OnGlobalLayoutListener 或 view.post(() -> ...) 中設置 |
| 百分比值不生效 | XML 用 50%,代碼用 0.5f(像素) | 代碼中手動換算:view.getWidth() * 0.5f |
| 旋轉後位置偏移 | 旋轉改變邊界,後續布局受影響 | 用 translationX/Y 修正,或改用 animation 而非屬性動畫 |
**口訣**:「pivot 是釘子,動畫繞著釘子轉」。要釘在哪,pivotX/Y 就設在哪——相對 View 左上角,支持像素、自百分比、父百分比三種單位。