Android imageView 的放大和縮小?


本例演示瞭如何放大和縮小 Android ImageView。

步驟 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" xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="16dp"
   android:gravity="center"
   tools:context=".MainActivity">
   <ImageView
      android:id="@+id/imageView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:src="@drawable/image" />
</LinearLayout>

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

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
   private ScaleGestureDetector scaleGestureDetector;
   private float mScaleFactor = 1.0f;
   private ImageView imageView;  
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      imageView=findViewById(R.id.imageView);
      scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
   }
   @Override
   public boolean onTouchEvent(MotionEvent motionEvent) {
      scaleGestureDetector.onTouchEvent(motionEvent);
      return true;
   }
   private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
      @Override
      public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
         mScaleFactor *= scaleGestureDetector.getScaleFactor();
         mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
         imageView.setScaleX(mScaleFactor);
         imageView.setScaleY(mScaleFactor);
         return true;
      }
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行你的應用程式。我認為你已將 Android 手機與電腦相連。要透過 Android Studio 執行應用程式,請開啟你的其中一個專案的活動檔案,然後單擊工具欄上的“執行 播放圖示 " 圖示。選擇你的移動裝置作為選項,然後檢視會顯示預設介面的你的移動裝置 −

更新時間:2020 年 7 月 7 日

6000 次以上檢視

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告