在我正在开发的游戏中,我需要调整可绘制对象的大小,因此我找到了一段代码来完成我想要的。假设为了简单起见,我想将所有内容的大小调整为 ButtonWidth/2、ButtonHeight/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; 
} 

后来,我发现这个过程会泄漏内存(特别是“return”行),所以我将这个方法改为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 中做同样的事情吗?

注意:我所说的“有效”是指“调整大小”。我可以在屏幕上查看可绘制对象是否已调整大小。

请您参考如下方法:

回答参数传递问题:

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

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

然后调用doSomething (myObject);

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


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java之如何通过付款找到利率