Wednesday, October 7, 2009

AS3: Alpha for Sprite that has children

This one caught me out. I was wondering why I could not change the alpha of a bitmap that I had added as a child of a Sprite. Consider this code block:
var my_sprite:Sprite = new Sprite();

my_sprite.graphics.beginFill(0x000000);
my_sprite.graphics.lineStyle(1, 0x111111, 1, false,
"normal", null, null, 3);
my_sprite.graphics.drawRect(0, 0, 400, 500);
my_sprite.graphics.endFill();
my_sprite.alpha = 0.3; // This is not correct. Will affect all children

stage.addChild(my_sprite);

my_sprite.addChild(my_bitmap); // Some valid bitmap

my_bitmap.alpha = 1; // Does not work.
What I expected was that the sprite would be translucent and my bitmap would be solid. However I found the bitmap taking on the alpha of the sprite. The reason for that was I should not have been trying to change the Sprite's alpha rather I needed to use the alpha parameter of the beginFill call. So the correct code would be:
var my_sprite:Sprite = new Sprite();

my_sprite.graphics.beginFill(0x000000, 0.3); // Alpha of 0.3 for the fill
my_sprite.graphics.lineStyle(1, 0x111111, 1, false,
"normal", null, null, 3);
my_sprite.graphics.drawRect(0, 0, 400, 500);
my_sprite.graphics.endFill();

stage.addChild(my_sprite);

my_sprite.addChild(my_bitmap); // Some valid bitmap

my_bitmap.alpha = 1; // This will work now

3 comments: