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

Android 圖片旋轉指定角度:使用 Matrix 而非 RotateAnimation 避免回彈

     編輯:程式設計綜合問答

問題現象

使用 RotateAnimation 旋轉指南針圖片,動畫結束後圖片瞬間回到原角度(預設 fillAfter=false)。

根本原因

RotateAnimation 預設不保持最終狀態,需設定 setFillAfter(true),但動畫層與視圖層分離,仍易出現閃爍/點擊區域未旋轉等問題。

正確方案:Matrix 直接修改視圖矩陣


ImageView arrow = findViewById(R.id.arrow);
float bearing = myLocation.bearingTo(target);  // 目標角度

Matrix matrix = new Matrix();
arrow.setScaleType(ImageView.ScaleType.MATRIX);  // 關鍵:啟用 Matrix 模式
matrix.postRotate(bearing, arrow.getWidth()/2f, arrow.getHeight()/2f);  // 以中心旋轉
arrow.setImageMatrix(matrix);

關鍵點

  • setScaleType(MATRIX):讓 ImageView 使用 ImageMatrix 繪製,而非預設 FIT_CENTER。
  • postRotate(degrees, px, py):以 (px, py) 為中心旋轉,通常用圖片中心。
  • 無動畫、無回彈、即時生效、觸摸區域同步旋轉。

進階:帶動畫旋轉


ObjectAnimator animator = ObjectAnimator.ofFloat(arrow, "rotation", currentAngle, targetAngle);
animator.setDuration(300);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.start();
// 同時更新 Matrix 保持最終狀態
animator.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        Matrix m = new Matrix();
        m.postRotate(targetAngle, arrow.getWidth()/2f, arrow.getHeight()/2f);
        arrow.setImageMatrix(m);
    }
});

常見誤區

  • 只用 RotateAnimation 不設 fillAfter:動畫結束視圖恢復原狀。
  • 用 View.setRotation() (API 11+):簡單但不支援舊版本,且不改變 Matrix 可能影響縮放/平移組合。
  • 忽略樞紐點:預設旋轉中心為 View 左上角 (0,0),指南針必須指定中心點。

總結

靜態旋轉用 Matrix,動態旋轉用 ObjectAnimator + Matrix 收尾。拋棄 RotateAnimation 這個舊 API,擁抱屬性動畫與 Matrix 的組合。

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