Copy and Paste Images in Adobe Air
Posted by CesareAfter learning drag and drop we will dig into copy and paste. We have already seen how to use the clipboard class to temporary store data during the drag action. Now we will use the same class to copy and paste an image within an Adobe Air application. We will start with the following layout.
This corresponds to the following mxml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="#222222" color="#f5f5f5" layout="vertical"> <!-- Feedback --> <mx:Text id="feedback" height="20"/> <!-- Image to copy --> <mx:Image id="im" source="logo.png"/> <!-- Commands --> <mx:HBox> <mx:Button label="copy" click="copyToClipboard()"/> <mx:Button label="paste" click="pasteFromClipboard()"/> <mx:Button label="clear" click="Clipboard.generalClipboard.clearData(ClipboardFormats.BITMAP_FORMAT)"/> </mx:HBox> <mx:VBox id="copies" width="{im.width}"/> </mx:WindowedApplication> |
Let’s have a look at the copy mechanism. We want to be sure that, before copying, the clipboard has no bitmap (line 3). Then we create a BitmapData object to store the content of the image (lines 4-5) and we put it in the clipboard (line 6). We gently provide some feedback (line 7).
1 2 3 4 5 6 7 8 9 | private function copyToClipboard():void { Clipboard.generalClipboard.clearData(ClipboardFormats.BITMAP_FORMAT); var data:BitmapData = new BitmapData(im.width, im.height); data.draw(im); // this copies the content in the clipboard Clipboard.generalClipboard.setData(ClipboardFormats.BITMAP_FORMAT, data); feedback.text = "Data have been copied"; } |
The paste mechanism is pretty similar to the one illustrated in previous tutorials. We read data from the clipboard (line 3), create a new Image class to store the Bitmap and then add it to the duplicates area (lines 4-7).
1 2 3 4 5 6 7 8 9 | private function pasteFromClipboard():void { var b:Bitmap = new Bitmap(Clipboard.generalClipboard.getData(ClipboardFormats.BITMAP_FORMAT) as BitmapData); var i:Image = new Image(); i.height = b.height; i.addChild(b); copies.addChild(i); } |
This is the intended result.
Source code is available.
Next time we will see how to copy and paste a complex object.


Leave a Reply