4

私のアプリは SD カードから多くのビットマップをデコードするため、既存のビットマップを再利用して GC 作業を減らしたいと考えています。Android Trainingこのビデオの例を見て、 BitmapFactory.decodeResource では完璧に機能しますが、 BitmapFactory.decodeFileでは機能しませ。次のコードを使用します。

private void testBitmapReusing() {
        BitmapFactory.Options options = newOptions();
        Bitmap bitmap = decode(options);

        options.inBitmap = bitmap;
        bitmap = decode(options);
    }

    private BitmapFactory.Options newOptions() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inMutable = true;
        return options;
    }

    private Bitmap decode(BitmapFactory.Options options) {
        return  BitmapFactory.decodeFile("/mnt/sdcard/sun.jpg", options);
        //  return BitmapFactory.decodeResource(getResources(), R.drawable.sun, options);
    }

コメント付きコード ( BitmapFactory.decodeResource) は期待どおりに機能し、既存のビットマップを使用して新しいビットマップをデコードします。しかし、コメントを外したコード ( BitmapFactory.decodeFile) は、新しいビットマップをデコードしません。ログメッセージに「E/BitmapFactory: ストリームをデコードできません: java.lang.IllegalArgumentException: 既存のビットマップへのデコードに問題があります」と書き込むだけです。

それで、私の間違いはどこですか?

更新 私は自分の失敗に気づきました。GIF 画像をデコードしようとしましたが、GIF 形式のビットマップを再利用することはできません。ドキュメントには次のように書かれています:

The source content must be in jpeg or png format (whether as a resource or as a stream)
4

1 に答える 1

0

直接探しているものではないかもしれませんが、別の方法として、マップ (HashMap など) を作成し、リソースが呼び出されたらすぐに追加することもできます。このようなもの:

HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();

public Bitmap loadBitmap(String location) {
    if (map.containsKey(location))
        return map.get(location);

    Bitmap bmp = yourDecodeMethod(location);
    map.put(location, bmp);

    return bmp;
}

これは、毎回リソースをリロードしたくない場合に使用するのと同じ方法です。これがあなたのやりたいことではない場合は申し訳ありませんが、私はあなたの実際の目標を理解するために最善を尽くしました:)

幸運を!

于 2013-08-23T22:44:18.697 に答える