使用 RotateAnimation 旋轉指南針圖片,動畫結束後圖片瞬間回到原角度(預設 fillAfter=false)。
RotateAnimation 預設不保持最終狀態,需設定 setFillAfter(true),但動畫層與視圖層分離,仍易出現閃爍/點擊區域未旋轉等問題。
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);
}
});
靜態旋轉用 Matrix,動態旋轉用 ObjectAnimator + Matrix 收尾。拋棄 RotateAnimation 這個舊 API,擁抱屬性動畫與 Matrix 的組合。