重新缩放位图时的内存问题

时间:2015-11-25 14:35:29

标签: android bitmap

所以,我有这个测试项目,我试图通过位图来圈出我发现的问题,并且我在调整位图大小时遇到​​了比平常更多的问题。该项目,预调整大小测试,允许我从流中加载位图,显示它并处理它。在循环中。

protected override void OnCreate (Bundle bundle){
    ...
    int i = 0;
    System.Timers.Timer t = new System.Timers.Timer (100);
    t.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e) {
        RunOnUiThread(delegate() {
            if(i++ % 2 == 0){
                Console.WriteLine("Iteration no: " + i);
                tmpView tView = new tmpView(this);
                mainView.AddView(tView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
            }else{
                 ((tmpView)mainView.GetChildAt(0)).dispose();
                 mainView.RemoveAllViews();
            }
        });

    };
    t.AutoReset = true;
    t.Start ();
}

和tmpView代码:

private class tmpView:RelativeLayout{
    PTImage img;
    ImageView img2;
    PTImageObj imgObj;
    Android.Graphics.Bitmap bmp;
    Bitmap resized;
    public tmpView(Context cntx):base(cntx){
        SetBackgroundColor(new Android.Graphics.Color(200, 0, 0, 200));
        System.IO.Stream imgStream = Application.Context.Assets.Open ("backgroundLeft.png");
        bmp = Android.Graphics.BitmapFactory.DecodeStream (imgStream, new Android.Graphics.Rect(), new Android.Graphics.BitmapFactory.Options(){InPurgeable = true, InInputShareable = true});
        img2 = new ImageView(cntx);
        img2.SetImageBitmap(bmp);
        imgStream.Close();
        imgStream.Dispose();
        GC.SuppressFinalize(imgStream);
        imgStream = null;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, 500);
        lp.TopMargin = 150;
        this.AddView(img2, lp);
    }

    public void dispose(){
        bmp.Recycle ();
        img2.SetImageDrawable (null);
    }
}

到目前为止工作正常,我可以在没有outOfMemory问题的情况下让它迭代。但是,如果我想将tmpView代码更改为:

public tmpView(Context cntx):base(cntx){
    SetBackgroundColor(new Android.Graphics.Color(200, 0, 0, 200));
    System.IO.Stream imgStream = Application.Context.Assets.Open ("backgroundLeft.png");
    bmp = Android.Graphics.BitmapFactory.DecodeStream (imgStream, new Android.Graphics.Rect(), new Android.Graphics.BitmapFactory.Options(){InPurgeable = true, InInputShareable = true});
    resized = Bitmap.CreateScaledBitmap(bmp, bmp.Width + 50, bmp.Height + 50, false);
    bmp.Recycle();
    img2 = new ImageView(cntx);
    img2.SetImageBitmap(resized);
    imgStream.Close();
    imgStream.Dispose();
    GC.SuppressFinalize(imgStream);
    imgStream = null;
}

我在大约200次迭代时结束了outOfMemory问题。我的猜测是重新缩放是创建临时位图,我无法强制回收。有没有更好的方法来调整位图的大小,以便我可以继续循环而不会崩溃?

注意:如果我实际上没有调整大小,如果我给位图具有相同大小的CreateScaledBitmap,我就不会遇到内存问题。但是......那种失败的目的:P。哦,是的,我确实在resized.Recycle ();

中添加了dispose

注意2:代码在C#中,但我可以使用java中的答案

谢谢,

阿克塞尔

0 个答案:

没有答案