1

所以我对 Android 开发人员还很陌生,而且我在使用 ImageViews 时遇到了一个奇怪的问题。非常欢迎任何指示或建议!

我正在为我的 ImageViews 动态设置位图,这有点工作。除了它们有时只显示图像,其余时间我用近似图像颜色进行全彩色填充,如下所示。

截屏

我认为他们正在使用我从 Android 论坛获得的这段代码正确扩展,所以我认为我没有遇到内存问题......

public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream,null,options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeStream(inputStream,null,options);
    }
4

1 回答 1

1

经过几个小时的研究,我终于发现,由于我使用 AsyncTask 来促进这些位图的加载,它们有时比主 UI 线程更快。myImageView.getHeight()当我调用& width()时,这把我搞砸了。

所以这是我想出的解决方案,希望它可以帮助其他人:

public class DecodeTask extends AsyncTask<String, Void, Bitmap> {

public ImageView currentImage;
private static AssetManager mManager;

public DecodeTask(ImageView iv, AssetManager inputManager) {
    currentImage = iv;
    mManager = inputManager;
}

protected Bitmap doInBackground(String... params) {

    int bottomOut = 1000;
    while(currentImage.getMeasuredWidth() == 0 && currentImage.getMeasuredHeight() == 0 && (--bottomOut) > 0)
    {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    InputStream iStream = null;
    Bitmap bitmap = null;
    try {
        iStream = mManager.open("photos" + File.separator + params[0]);

        bitmap = ImageUtils.decodeSampledBitmapFromStream(iStream, currentImage.getMeasuredWidth(), currentImage.getMeasuredHeight());

        iStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
    if(currentImage != null) {
        currentImage.setImageBitmap(result);
        currentImage.invalidate();
    }
}

}
于 2012-12-26T23:16:45.667 回答