图像不适合ImageButton-Kotlin Android Studio



我在Android Studio中使用Kotlin创建了一个表单,用户可以通过使用相机拍照来附加图像。一旦用户点击ImageButton,相机就会启动,用户就可以拍照了。然后应在ImageButton中设置捕捉到的照片。这是有效的,但是,图像太大,不能很好地放在ImageButton中。相反,它扩展了ImageButton。

以下是before和after的屏幕截图:
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"属性

最新更新