Kotlin 使用 Android imageView 放大和縮小?
本示例演示如何使用 kotlin 實現 Android imageView 放大和縮小。
步驟 1 − 在 Android Studio 中建立新專案,轉到 File ⇒ New Project,然後填寫所有必需資訊以建立新專案。
步驟 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:gravity="center" android:orientation="vertical" android:padding="16dp" 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.kt
import android.os.Bundle import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import kotlin.math.max import kotlin.math.min class MainActivity : AppCompatActivity() { private lateinit var scaleGestureDetector: ScaleGestureDetector private var scaleFactor = 1.0f private lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" imageView = findViewById(R.id.imageView) scaleGestureDetector = ScaleGestureDetector(this, ScaleListener()) } override fun onTouchEvent(motionEvent: MotionEvent): Boolean { scaleGestureDetector.onTouchEvent(motionEvent) return true } private inner class ScaleListener : SimpleOnScaleGestureListener() { override fun onScale(scaleGestureDetector: ScaleGestureDetector): Boolean { scaleFactor *= scaleGestureDetector.scaleFactor scaleFactor = max(0.1f, min(scaleFactor, 10.0f)) imageView.scaleX = scaleFactor imageView.scaleY = scaleFactor 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.q11"> <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 移動裝置連線到計算機。要從安卓工作室執行應用程式,請開啟你的一個專案活動檔案,並單擊工具欄中的執行圖示 。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕
廣告