如何将位图设置为imageView?

时间:2015-09-08 09:51:46

标签: android bitmap imageview

我一直在努力将图像(我使用uri获取)设置为ImageView

我在做什么?

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<Attachment> imageViewReference;

    public BitmapWorkerTask(Attachment imageView) {
        // Use a WeakReference to ensure the ImageView can be garbage collected
        imageViewReference = new WeakReference<Attachment>(imageView);
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        return ImageResizer.decodeSampledBitmapFromFile(imageViewReference.get().getPath(), 200, 100);
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final Attachment imageView = imageViewReference.get();
            if (imageView != null) {
                profilePic.setImageBitmap(bitmap);
            }
            else {
                Log.v("BLAH[Inner]", (imageViewReference ==null) +""+(bitmap == null));
            }
        }
        else {
            Log.v("BLAH", (imageViewReference ==null) +""+(bitmap == null));
        }
    }
}

我已经确认uri是正确的,并且图像的绝对路径也是正确的(在Attachment对象的path属性中设置).Plus位图不为空。

但是imageView仍未显示图像。

更新 图像没有在第一次显示,但在此之后每次都有效。奇怪的是,logcat上也没有显示任何内容。

警告

使用错误的变量名称(重构出错)

默认图像(在xml中设置)确实显示。看看

Default image

我使用了层次结构查看器来检查布局。

Here's what it looks like...

4 个答案:

答案 0 :(得分:0)

我希望你在manifest中添加了权限:

'Admin'

有时我们会想念小事。

答案 1 :(得分:0)

您使用的setImageBitmap始终有效,但您可以使用以下代码段。

BitmapDrawable ob = new BitmapDrawable(getResources(), bitmap)
imageView.setBackgroundDrawable(ob);

答案 2 :(得分:0)

更改

profilePic.setImageBitmap(bitmap)

imageView.setImageBitmap(bitmap)

答案 3 :(得分:0)

根据您提供的信息,似乎文件有问题,或者ImageResizer.decodeSampledBitmapFromFile无法正常工作,返回空的或透明的位图。

您可以在onPostExecute中添加此代码并发布结果吗?

int width = bitmap.getWidth();
int height = bitmap.getHeight();
Log.v("BLAH", "width : " + width);
Log.v("BLAH", "height : " + height);
if(width > 0 && height > 0) {
    Log.v("BLAH", "pixel : " + bitmap.getPixel(width/2,height/2));
}
相关问题