在 Android Studio 中使用 Kotlin,我創建了一個表單,用戶可以在其中通過使用相機拍照來附加影像。一旦用戶單擊 ImageButton,相機將啟動,用戶可以拍照。然后應在 ImageButton 中設定捕獲的照片。這可行,但是,影像太大,不能很好地適合 ImageButton。相反,它擴展了 ImageButton。
以下是之前和之后的螢屏截圖:
之前
之后- 從螢屏截圖中可以看出,影像不適合原本為方形的 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)
}
}
}
}
}
uj5u.com熱心網友回復:
代碼:android:layout_height="wrap_content"允許按鈕擴展到影像的大小。
有兩種解決方案,
- 使用小尺寸圖片
- 將限制添加到高度而不是
"wrap_content"屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436288.html
