首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 動畫 pivotX/pivotY 詳解:縮放旋轉的樞紐點

     編輯:程式設計綜合問答

定義

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" />
  • 中心縮放:View 向四周均勻縮小,中心點不動。
<scale
    android:pivotX="0%" android:pivotY="0%"
    ... />
  • 左上角縮放:左上角固定,View 向右下方收縮。
<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 左上角,支持像素、自百分比、父百分比三種單位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved