如何正确缩放导入的图片使其适配Android的ImageView?
适配方案
- 第一步:替换原生
setImageUri方法,手动解码Uri对应图片适配控件尺寸
原生setImageUri未做尺寸适配,会默认遵循系统资源展示规则,容易出现随系统图标样式裁剪的问题,可添加如下工具方法实现自定义适配:
// 把该方法添加到你的适配器或者所在Activity/Fragment中 private void setImageFromUri(ImageView imageView, String uriStr) { Uri uri = Uri.parse(uriStr); try { // 获取目标控件尺寸,未测量完成则用预设的120dp转像素值 int targetW = imageView.getWidth(); int targetH = imageView.getHeight(); if (targetW == 0 || targetH == 0) { float density = getResources().getDisplayMetrics().density; targetW = targetH = (int) (120 * density); } // 预解码仅获取图片尺寸,不占用内存 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; InputStream inputStream = getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); // 计算采样率,降低图片加载内存占用 int photoW = options.outWidth; int photoH = options.outHeight; int scaleFactor = Math.max(1, Math.min(photoW / targetW, photoH / targetH)); // 最终解码图片 options.inJustDecodeBounds = false; options.inSampleSize = scaleFactor; options.inPurgeable = true; InputStream newInputStream = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(newInputStream, null, options); newInputStream.close(); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); // 异常时可在此处设置占位图 } }
- 第二步:调整布局属性,固定展示规则
修改ImageButton的缩放属性,明确关闭系统默认裁剪逻辑,修改后的完整布局如下:
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView android:layout_height="120dp" android:id="@+id/foodlay" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" xmlns:app="http://schemas.android.com/apk/res-auto" app:cardElevation="10dp" app:cardCornerRadius="20dp" android:layout_width="120dp" xmlns:android="http://schemas.android.com/apk/res/android"> <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" <!-- 按需选择缩放类型:centerCrop=填充控件不留白,fitCenter=完整展示图片 --> android:scaleType="centerCrop" android:adjustViewBounds="true" android:cropToPadding="false" android:id="@+id/imago" android:background="@null" /> </androidx.cardview.widget.CardView>
- 第三步:替换适配器调用逻辑
把原来的Img.setImageUri(cursor.getString(6))替换为setImageFromUri(Img, cursor.getString(6))即可。
内容的提问来源于stack exchange,提问作者Piotr Tomasik
相关产品推荐
相关产品推荐

