How to copy displayed objects (sprites, movie clips, etc.), saving their contents (graphics, added display objects, etc.) in AS3? The most commonly proposed Kirupa solution (http://www.kirupa.com/forum/showpost.php?p=1939827&postcount=172) does not seem to copy graphic or child display objects:
// create a sprite var s:Sprite = new Sprite(); // add a text field var tf:TextField = new TextField(); tf.text = "nisse"; s.addChild(tf); // draw something s.graphics.lineStyle(1, 0x00FF00); s.graphics.drawCircle(10, 10, 10); s.x=100; // add it to parent this.addChild(s); // create a copy using Kirupas duplicate display object solution var sCopy:Sprite = duplicateDisplayObject(s, true) as Sprite; sCopy.x = 200; // confirem that the copy exists: trace(sCopy); // add to parent this.addChild(sCopy); // <- works, but the original textfield and graphics are gone!
Is there any for this? (If not, why? Is not the displayed object represented by the memory area that can be copied like any other object?)
Short answer:
. , , , , . ( , , .)
:
DisplayObject - , . , , .. , , , , . , , ? - , , , ? , ? Et cetera, et cetera.
- , (, AS3) . , MovieClips, - , , -, Kirupa. , , , , . - , .
, , , . , . , , , , , . , , , , , .
, , .
, IExternalizable (http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/utils/IExternalizable.html)
, AMF. : readExternal writeExternal. , writeExternal ByteArray, , AMF ByteArray readExternal, . ObjectUtil.copy() (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/ObjectUtil.html?filter_flex=4.1&filter_flashplayer=10.1&filter_air=2#copy()), Flex SDK, :
function copy(value:*):*{ var buffer:ByteArray = new ByteArray(); buffer.writeObject(value); buffer.position = 0; var result:Object = buffer.readObject(); return result; }
, readObject writeObject ByteArray , ObjectUtil.
, , AMF , , :
registerClassAlias("com.example.ExampleClass", com.example.ExampleClass);
, , , ByteArray readObject , , IExternalizable, . .
Display , :
FP 10, Graphics .
public function copyFrom(sourceGraphics:Graphics):void
(http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Graphics.html#copyFrom())
, , . copy(). , Sprite MovieClip, copyFrom(). .
.
public function drawGraphicsData(graphicsData:Vector.<IGraphicsData>):void
(http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Graphics.html#drawGraphicsData())
( JSON DTO), IExternalizable, Object Graphics, . , , copy(), , , - copy(). , FP9, . , , . , .
, AS3 - , , , - clone():) , , .
You cannot make an exact copy, but you can easily create a surrogate bitmap. Which works for me in most cases (fills, thumbnails, etc.)
See the Drawmap BitmapData method.
var newObject:DisplayObject; newObject = originalObject; addChild(newObject);
This is how I do it. It worked with all types of display objects (mc, sprites, textField, etc.)