Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片處理:讓圖片持續等速旋轉

編輯:關於 Android 程式設計

這篇可以接在先前那篇「讓圖片變成圓形」之後看,單獨閱讀也沒問題。

步驟一:建立 anim 資源目錄

在 res 資料夾下新增一個名為 anim 的目錄,名稱不要打錯。

步驟二:撰寫旋轉動畫定義檔

在 anim 裡新增 img_animation.xml(檔名可自取,但避免大寫):

 <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="https://schemas.android.com/apk/res/android" > <rotate android:duration="5000" android:fromDegrees="0" android:pivotX="50%" android:pivotY="50%" android:repeatCount="-1" android:repeatMode="restart" android:toDegrees="360" /> </set>

各屬性含義:

duration:動畫 duration,單位毫秒
fromDegrees="0":起始角度
toDegrees="360":旋轉總角度
pivotX="50%"/pivotY="50%":旋轉中心相對於 View 左上角的位置,這裡設為正中央
repeatCount="-1":重複次數,-1 代表無限循環
repeatMode="restart":重複模式,restart 表示每次都從頭轉起

步驟三:布局

布局檔不用改,放一個控件就好:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff00ff" > <com.example.circleimageview.CircleImageView android:id="@+id/imageview" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerInParent="true" android:src="@drawable/control_image" /> </RelativeLayout>

换成一般的 ImageView 也一樣能轉。

步驟四:套用動畫

 package com.example.circleimageview; import android.app.Activity; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.widget.ImageView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = (ImageView) findViewById(R.id.imageview); //載入動畫 Animation animation = AnimationUtils.loadAnimation(this, R.anim.img_animation); LinearInterpolator lin = new LinearInterpolator();//設定為等速運動 animation.setInterpolator(lin); imageView.startAnimation(animation); } }

這裡的 LinearInterpolator 是重點。若不指定插值器,系統預設會套用加速減速效果,轉起來忽快忽慢;換成 LinearInterpolator 才是真正意義上的等速旋轉。

實際運行效果(錄影有些掉幀,實機是平順的等速旋轉):

整體來說非常簡單:一個 XML 描述旋轉規則,一行 setInterpolator 決定速度曲線,再 startAnimation 就完成了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved