android - BitmapFactory 从可绘制对象和文件返回位图的不同大小

标签 android bitmap imageview

我有同一张图像的两份副本。其中一个位于应用程序的资源文件夹(默认可绘制)内,另一个位于外部存储上。

我使用以下代码获取位图:

 // Get from storage
 BitmapFactory.decodeFile(image.getAbsolutePath());

 // Get from resource
 BitmapFactory.decodeResource(getResources(), R.drawable.image);

但是,它们会导致 ImageView 中的高度和宽度与 wrap_content 不同。我该如何解决这个问题?

最佳答案

此行为是由于 BitmapFactory 的实现造成的。在从 decodeResource 调用 decodeResourceStream 期间,它将分配一个 BitmapFactory.Options 并将 inDensity 设置为 如果 BitmapFactory.Options 为 null,则 DisplayMetrics.DENSITY_DEFAULT

另一方面,decodeFile 通过 setDensityFromOptions 传递,如果 BitmapFactory.Options 为 null,则立即返回。

因此,解决方案之一是通过以下代码来缩放decodeFile的密度。

BitmapFactory.Options option = new BitmapFactory.Options();
option.inDensity = DisplayMetrics.DENSITY_DEFAULT;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), option);

如果你想反向执行,可以使用以下代码。

InputStream inputStream = context.getResources().openRawResource(R.drawable.image);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

注意,会出现“常量和资源类型不匹配”的情况,但仍然可以编译。 decodeResource 还将 openRawResource 调用为 InputStream,所以这很好。

关于android - BitmapFactory 从可绘制对象和文件返回位图的不同大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37922725/

相关文章:

Android:使用 SurfaceView 时如何支持多种屏幕分辨率

android - Android中从httpResponse获取图片内容

安卓:BitmapFactory.decodeResource 返回 null

java - LinearLayout 无法转换为 android.widget.ImageView?

RecyclerView 中的 Android RecyclerView?

java - ViewPager 卡住了

android - 广告无法在 Android 中加载

android - AmazonRDS、Rails 和安卓

java - 在 DialogFragment 从网站下载图片后,ImageView 上方出现青色条

android - 自定义 ImageView、ImageMatrix.mapPoints() 和 invert() 不准确?