Friday, April 22, 2011

Working with clipboard in AIR: Part 9

In this tutorial we'll learn how to be able to drag an image from our AIR application to an application outside of it.

I will be creating a simple application with an image that can be dragged outside of the AIR application, for example, to Microsoft Word. The data will be passed in the clipboard as a BitmapData object, this is why I picked Word for this tutorial - Word can read bitmap data from the clipboard and turn it into an image.

First of all we need to put our image on stage. You can use UILoader for this, or just a simple MovieClip with the image as its content. Make sure the registration point is at the top left corner, though (this is needed to cut the bitmap correctly).

The image can be turned into a BitmapData object by creating a new object of the said class and drawing our object into it:

var bitmapData:BitmapData = new BitmapData(myObject.width,myObject.height);
bitmapData.draw(myObject);

Next we create the clipboard. We are working with bitmaps and we want to pass bitmap data, so we need to set the Clipboard Format as BITMAP_DATA.

var myClip:Clipboard = new Clipboard();
myClip.setData(ClipboardFormats.BITMAP_FORMAT, bitmapData);

Create a point object to display the half-transparent object clone when dragging correctly, and call the already known doDrag() method, entering 4 parameters - the object, clipboard, cursor image and the point object.

var objPoint:Point = new Point( -  myObject.mouseX, -  myObject.mouseY);
NativeDragManager.doDrag(myObject, myClip, bitmapData, objPoint);

This whole construction is called when we press our mouse down on the object:

import flash.desktop.Clipboard;
import flash.display.BitmapData;
import flash.geom.Point;

myObject.addEventListener(MouseEvent.MOUSE_DOWN, mDown);

function mDown(MouseEvent):void
{
var bitmapData:BitmapData = new BitmapData(myObject.width,myObject.height);
bitmapData.draw(myObject);
var myClip:Clipboard = new Clipboard();
myClip.setData(ClipboardFormats.BITMAP_FORMAT, bitmapData);
var objPoint:Point = new Point( -  myObject.mouseX, -  myObject.mouseY);
NativeDragManager.doDrag(myObject, myClip, bitmapData, objPoint);
}

Now if you test this and try dragging the object into Word, it will paste a clone of this image in the Word document area.

Thanks for reading!

Related:

Working with clipboard in AIR: Part 1
Working with clipboard in AIR: Part 2
Working with clipboard in AIR: Part 3
Working with clipboard in AIR: Part 4
Working with clipboard in AIR: Part 5
Working with clipboard in AIR: Part 6
Working with clipboard in AIR: Part 7
Working with clipboard in AIR: Part 8
Working with clipboard in AIR: Part 10

1 comment:

Anonymous said...

Thanks a lot Krill

Post a Comment