如何获取附加到ImageView的整个位图?

9
我试图使用ImageView.getDrawingCache();获取与ImageView相关联的位图,但我发现返回的位图与我想从ImageView中获取的位图不同。它总是比实际图像小。
我知道,如果视图大于屏幕,则方法getDrawingCache()不应该有视图,因为只绘制可见部分,并且缓存仅保存已绘制的内容。
我能否获取与ImageView相关联的整个位图?
3个回答

26
如果您只想从 ImageView 获取 Bitmap,则以下代码可能适用于您:
Bitmap bm=((BitmapDrawable)imageView.getDrawable()).getBitmap();

我想那就是你想要的。


我总是遇到NPE错误:尝试调用虚拟方法'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()'。 - josher932
有时getDrawable可能会返回其他对象..你可能会遇到对象转换异常。 - Ravi
@josher932 你可能想要检查 mipreamble 的答案。不过我建议你检查为什么会出现空指针,因为这并不正常。 - 0xC0DED00D
@Ravi 显然它会返回一个Drawable,但它可能不是BitmapDrawable类的对象。因此,您需要检查您得到了什么类型的Drawable。 mipremble的答案在这方面要好得多。 - 0xC0DED00D

14

如果您的drawble并非始终是BitmapDrawable的一个实例

注意:在执行此操作之前,应先设置ImageView。

Bitmap bitmap;
if (mImageView.getDrawable() instanceof BitmapDrawable) {
    bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
    Drawable d = mImageView.getDrawable();
    bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    d.draw(canvas);
}

你的位图存储在bitmap中。

完成!


-1

最简单的方法是在ImageView中设置标签。

imageView.setImageBitmap(bitmap);
imageView.setTag(bitmap); 

从中获取标签

imageView.getTag();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接