我进行了 3 次测试以检查位图是按值传递还是按引用传递,但在运行以下代码后感到困惑:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
V v = new V(this);
setContentView(v);
}
class V extends View{
Bitmap b1;
Bitmap b2;
public V(Context context) {
super(context);
//load bitmap1
InputStream is = getResources().openRawResource(R.drawable.missu);
b1 = BitmapFactory.decodeStream(is);
//testing start
b2 = b1;
//b1 = null;
//1.test if b1 and b2 are different instances
if(b2 == null){
Log.d("","b2 is null");
}
else{
Log.d("","b2 still hv thing");
}
//2.test if b2 is pass by ref or value
test(b2);
if(b2 == null){
Log.d("","b2 is null00");
}
else{
Log.d("","b2 still hv thing00");
}
//3.want to further confirm test2
b2 = b2.copy(Config.ARGB_8888, true);
settpixel(b2);
if(b2.getPixel(1, 1) == Color.argb(255,255, 255, 255)){
Log.d("","b2(1,1) is 255");
}
else{
Log.d("","b2(1,1) is not 255");
}
}
void test(Bitmap b){
b = null;
}
void settpixel(Bitmap b){
b.setPixel(1, 1, Color.argb(255,255, 255, 255));
}
}}
结果:
b2 仍然是高压的东西
b2 仍然是 hv thing00
b2(1,1) 是 255
问题是测试 2 和 3 相互矛盾。test2 表明 b2 是按值传递的,因为 b2 没有变为空。但是如果位图是按值传递的,那么在 test3 中,setPixel() 应该在 b2(函数范围内的那个)的副本上工作,但是为什么 b2(外部范围)会改变它的像素值?ps 加载的位图是深红色的。