Search code examples
actionscript-3animate-cc

ActionScripts 3 How to replace/swap an image inside a stage?


I have some PNG image on a stage in Animate CC, how to possible change/swap an image with another PNG that imported to Library with code?


Solution

  • To add image from Library you need to set AS3 class (let it be image.flame) for that image and then

    import image.flame;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    
    var aRaster:BitmapData = new image.flame();
    var aBitmap:Bitmap = new Bitmap(aRaster);
    
    aBitmap.name = "Flame";
    addChild(aBitmap);
    

    Removing is a bit more tricky, probably.

    1) If Animate CC allows to name bitmap instances then you are in luck and can just name it (e.g. Flame) and then:

    removeChild(getChildByName("Flame"));
    

    1.1) Also you can wrap that bitmap with a MovieClip and give it a proper name. I think it is the most reliable way.

    2) If Animate CC does not allow to name bitmaps, just as CS6 that I have doesn't, then you are up to few options.

    2.1) If your bitmap is the only child in its container, just remove it with

    removeChildAt(0);
    

    2.2) If it is the only bitmap among some other content, you can find it and remove:

    for (var i:int = 0; i < numChildren; i ++)
    {
        var aChild:Bitmap = getChildAt(i) as Bitmap;
    
        if (aChild)
        {
            removeChild(aChild);
            break;
        }
    }
    

    2.3) If that bitmap is one of many, and there are other content in this container, well... guess its depth and removeChildAt(...) it, or go for option #1.1 and wrap that bitmap with a MovieClip for it to have instance name and available for removal.

    P.S. Just a side note, prior to CS6 I recall that Flash converted bitmaps (Bitmap class) into bitmap-filled shapes (Shape class), so #1.1 is your best friend anyway.