有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调整可绘图问题的大小(引用未被传递?)

在我正在开发的游戏中,我需要调整绘图的大小,所以我找到了一段代码,可以满足我的需要。假设为了简单起见,我想将所有内容调整为ButtonWidth/2、ButtonHeaght/2。以下是代码:

Drawable ResizeDrawable(Drawable image)
{
     Bitmap temp = ((BitmapDrawable)image).getBitmap();
     Bitmap resbit = Bitmap.createScaledBitmap(temp, ButtonWidth/2, ButtonHeight/2, true);
     Drawable ret = new BitmapDrawable(getResources(), resbit );
     return ret;
}

后来,我发现这个过程会泄漏内存(具体是“返回”行),所以我将这个方法改为void:

void ResizeDrawable(Drawable image)
{
     temp = ((BitmapDrawable)image).getBitmap();
     resbit = Bitmap.createScaledBitmap(temp, ButtonWidth/2, ButtonHeight/2, true);
     image = new BitmapDrawable(getResources(), resbit );
}

我知道Java会传递引用,所以这应该是可行的,但事实并非如此。不可行的完整代码:

//Variables are declared globally
Bitmap temp;
Bitmap resbit;
int ButtonWidth=100, ButtonHeight=100;

void TakeCareOfButtons() //I call this from OnCreate()
{
   MyDrawable = context.getResources().getDrawable(R.drawable.mydrawableresource);
   ResizeDrawable(MyDrawable);
}
void ResizeDrawable(Drawable image)
{
     temp = ((BitmapDrawable)image).getBitmap();
     resbit = Bitmap.createScaledBitmap(temp, ButtonWidth/2, ButtonHeight/2, true);
     image = new BitmapDrawable(getResources(), resbit );
}

所以我做的第一件事就是完全删除这个方法,然后手动调整每个可绘制的文件的大小,看看它是否有效。的确如此。有效的代码是:

//Variables are declared globally
Bitmap temp;
Bitmap resbit;
int ButtonWidth=100, ButtonHeight=100;//not the real values, but it's irrelevant now


    void TakeCareOfButtons() //I call this from OnCreate()
    {
         MyDrawable = context.getResources().getDrawable(R.drawable.mydrawableresource);
         temp = ((BitmapDrawable) MyDrawable).getBitmap();
         resbit = Bitmap.createScaledBitmap(temp, ButtonWidth/2, ButtonHeight/2, true);
         MyDrawable = new BitmapDrawable(getResources(), resbit );
    }

问题是:这两种代码不是等价的吗?他们不应该在Java中做同样的事情吗

注:我所说的“工作”是指“不调整大小”。我可以在屏幕上查看drawable是否已调整大小


共 (1) 个答案

  1. # 1 楼答案

    要回答通过辩论的问题:

    Java中的引用是按值传递的。这意味着,如果在一个接受对象参数的方法中,将new对象赋给该引用变量,如下所示:

    public void doSomething (Object bar){
      bar = new Object();
    }
    

    并致电doSomething (myObject);

    myObject修改为指向您的new Object ()