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 移动设备连接到计算机。要从安卓工作室运行应用程序,请打开你的一个项目活动文件,并单击工具栏中的运行图标 。选择你的移动设备作为选项,然后检查你的移动设备,它将显示你的默认屏幕

更新于: 05-Nov-2020

3K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.