【问题标题】:How to get bitmap from NetworkImageView?如何从 NetworkImageView 获取位图?
【发布时间】:2016-07-22 16:41:02
【问题描述】:

在我的项目中,我使用 (Volley + NetworkImageView) 下载了一些图像和文本并在列表视图中显示它们。直到这里,我没有任何问题。

现在,我想从 NetworkImageView 获取位图,我尝试了很多类似以下的方法,但没有一个对我有用。

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

另一种方法:

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();

他们都没有工作..

感谢任何帮助,

【问题讨论】:

    标签: android bitmap android-volley networkimageview


    【解决方案1】:

    您无法获取位图引用,因为它从未保存在 ImageView 中。 但是你可以使用:

    ((BitmapDrawable)this.getDrawable()).getBitmap();
    

    因为当你用 Volley 设置它时,你这样做:

    /**
     * Sets a Bitmap as the content of this ImageView.
     * 
     * @param bm The bitmap to set
     */
    @android.view.RemotableViewMethod
    public void setImageBitmap(Bitmap bm) {
        // Hacky fix to force setImageDrawable to do a full setImageDrawable
        // instead of doing an object reference comparison
        mDrawable = null;
        if (mRecycleableBitmapDrawable == null) {
            mRecycleableBitmapDrawable = new ImageViewBitmapDrawable(
                    mContext.getResources(), bm);
        } else {
            mRecycleableBitmapDrawable.setBitmap(bm);
        }
        setImageDrawable(mRecycleableBitmapDrawable);
    }
    

    但是,如果您以任何其他方式设置默认图像或错误图像或任何其他图像,您可能不会获得 BitmapDrawable,但会获得 NinePatchDrawable。

    检查方法如下:

    Drawable dd = image.getDrawable();
        if(BitmapDrawable.class.isAssignableFrom(dd.getClass())) {
            //good one
            Bitmap bb = ((BitmapDrawable)dd).getBitmap();
        } else {
            //cannot get that one
        }
    

    【讨论】:

    • 非常感谢你的回答,所以你的意思是我可以使用这样的东西:Bitmap btmap=((BitmapDrawable)this.getDrawable()).getBitmap();
    • 是的,我自己用过,但最好检查一下类型,否则你会得到一个 casttype 异常
    • 我收到此错误:致命异常:主进程:com.Activity,PID:24829 java.lang.ClassCastException:android.graphics.drawable.TransitionDrawable 无法转换为 android.graphics.drawable.BitmapDrawable在 com.SecondActivity$callOnClick.onClick(SecondActivity.java:233)
    • 非常感谢,我在 Android 6 中遇到了新权限样式的问题 :) 现在一切正常..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多