如何在Android中實現平滑的影像旋轉?


此示例演示如何在Android中實現平滑的影像旋轉。

步驟 1 - 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 - 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "18sp"
      android:textAlignment = "center"
      android:text = "rorate image"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
   <ImageView
      android:id = "@+id/rotateImage"
      android:layout_width = "match_parent"
      android:layout_marginTop = "10dp"
      android:layout_height = "wrap_content"
      android:src = "@mipmap/ic_launcher"
      android:layerType = "software" />
</LinearLayout>

在上面的程式碼中,我們使用了TextView和ImageView。當您點選TextView時,影像將沿逆時針方向旋轉。

步驟 3 - 將以下程式碼新增到src/MainActivity.java

package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView text;
   ImageView image;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      text = findViewById(R.id.text);
      image = findViewById(R.id.rotateImage);
      text.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            RotateAnimation rotate = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f,          Animation.RELATIVE_TO_SELF, 0.5f);
            rotate.setDuration(5000);
            rotate.setInterpolator(new LinearInterpolator());
            image.startAnimation(rotate);
         }
      });
}
}

在上面的程式碼中,我們使用了RotateAnimation類。它是Android中預定義的類。要使用以下程式碼旋轉影像 -

RotateAnimation rotate = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(5000);
rotate.setInterpolator(new LinearInterpolator());
image.startAnimation(rotate);

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android手機裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

在上面的程式碼中,它顯示了初始螢幕,當用戶點選TextView時,它將旋轉影像,如下所示 -

點選此處下載專案程式碼

更新於: 2019年7月30日

1K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告