获取Bitmap附加到ImageView

lem*_*mon 310 android imageview android-bitmap

特定

ImageView image = R.findViewById(R.id.imageView);
image.setImageBitmap(someBitmap);
Run Code Online (Sandbox Code Playgroud)

是否可以检索位图?

Ars*_*war 802

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
Run Code Online (Sandbox Code Playgroud)

  • 小心检查你的`image.getDrawable()`是否可以实际转换为`BitmapDrawable`(以避免`IllegalCastExceptions`).例如,如果你在图像中使用图层,那么这个片段会略有不同:`Bitmap bitmap =((BitmapDrawable)((LayerDrawable)image.getDrawable()).getDrawable(0)).getBitmap();` (33认同)
  • 如果从`URI`设置`ImageView`中的图像,这是否有效?`imageView.setImageUri()` (3认同)
  • 偶尔会返回带有部分或全部黑色像素的位图. (2认同)
  • 如果您已应用于drawable/imageview,则不会返回原始位图或过滤后的位图. (2认同)

Sar*_*fan 46

这将让你BitmapImageView.但是,它与您设置的位图对象不同.这是一个新的.

imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
Run Code Online (Sandbox Code Playgroud)

===编辑===

 imageView.setDrawingCacheEnabled(true);
 imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                   MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
 imageView.layout(0, 0, 
                  imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); 
 imageView.buildDrawingCache(true);
 Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
 imageView.setDrawingCacheEnabled(false);
Run Code Online (Sandbox Code Playgroud)

  • 给我一个空指针.:(在这一行:'Bitmap bmap = Bitmap.createBitmap(mImageView.getDrawingCache());` (3认同)
  • 它返回null.有时我必须重新加载页面才能实际显示. (2认同)