图片不适合 ImageButton - Kotlin Android Studio

Image does not fit in ImageButton - Kotlin Android Studio

在 Android Studio 中使用 Kotlin,我创建了一个表单,用户可以在其中通过使用相机拍照来附加图像。一旦用户单击 ImageButton,相机将启动,用户可以拍照。然后应在 ImageButton 中设置捕获的照片。这有效,但是,图像太大并且不适合 ImageButton。相反,它扩展了 ImageButton。

前后截图如下:
Before
After - 如屏幕截图所示,图像与最初为方形的 ImageButton 不太吻合。

我在网上进行研究时添加了 android:scaleType="fitXY",它适用于大多数人,但无济于事。我也试过 android:scaleType="fitCenter" 但没用。

XML代码:

<ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/submitButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        android:scaleType="fitXY"
        app:srcCompat="@mipmap/ic_camera_capture" />

.kt码

class FormActivity : AppCompatActivity() {

    lateinit var currentPhotoPath: String
    val REQUEST_IMAGE_CAPTURE = 1
    var selectedPhotoUri : Uri? = null

    companion object {
        const val REQUEST_FROM_CAMERA = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_formactivity)

        ...

        val imageButton = findViewById<ImageButton>(R.id.imageButton)

        // to launch the camera
        imageButton.setOnClickListener {
            takePictureUsingCamera()
        }
    }

    private fun takePictureUsingCamera(){
        ImagePicker.with(this).cameraOnly()
            .crop()
            .start(REQUEST_FROM_CAMERA)
    }

    // to access the image captured
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode){
                REQUEST_FROM_CAMERA -> {
                    selectedPhotoUri = data!!.data
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
                    val bitmapDrawable = BitmapDrawable(bitmap)

                    val imageButton = findViewById<ImageButton>(R.id.imageButton)
                    // add the image to the image button
                    imageButton.setImageDrawable(bitmapDrawable)
                }
            }

        }
    }
}

代码:android:layout_height="wrap_content" 允许按钮扩展到图像大小。

有两种解决方法,

  1. 使用小尺寸图片
  2. 添加高度限制而不是 "wrap_content" 属性。