提问人:Sabuj Ahmed 提问时间:5/27/2023 更新时间:6/2/2023 访问量:94
ImageView 适合宽度 100%,无需拉伸图像 android kotlin
ImageView fit width 100% without stretching the image android kotlin
问:
我从图库中获取图像,当我将图像添加到布局中时,如果图像大小小于宽度,则图像不会填充 100% 的宽度。我该怎么做?
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ig_gallery"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:layout_marginVertical="20dp"
android:src="@drawable/mypic"
app:layout_constraintBottom_toTopOf="@+id/button_pick"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
class MainActivity : AppCompatActivity() {
private val binding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.buttonPick.setOnClickListener {
pickImage()
}
}
private fun pickImage() {
ImagePicker.with(this)
.galleryOnly()
.compress(1024) //Final image size will be less than 1 MB(Optional)
.maxResultSize(
650,
1200
) //Final image resolution will be less than 1080 x 1080(Optional)
.createIntent { intent ->
startForProfileImageResult.launch(intent)
}
}
private val startForProfileImageResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
when (resultCode) {
Activity.RESULT_OK -> {
//Image Uri will not be null for RESULT_OK
val fileUri = data?.data!!
binding.igGallery.setImageURI(fileUri)
}
ImagePicker.RESULT_ERROR -> {
Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
}
else -> {
Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()
}
}
}
}
**我从图库中获取图像,当我将图像添加到布局中时,如果图像大小小于宽度,则图像不会填充 100% 的宽度。我该怎么做?
我尝试了很多,但没有得到任何结果**
答:
0赞
Ashfaque
6/2/2023
#1
试试这段代码
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ig_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:src="@drawable/mypic"
app:layout_constraintBottom_toTopOf="@+id/button_pick"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
0赞
Shaurya Singh
6/2/2023
#2
在代码中,您可以使用 android:scaleType 属性来控制图片在 ImageView 中的显示方式。要使图像填充布局的宽度,可以使用 fitXY 的 scaleType 值。代码如下:
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ig_gallery"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="fitXY"
android:layout_marginVertical="20dp"
android:src="@drawable/mypic"
app:layout_constraintBottom_toTopOf="@+id/button_pick"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
评论