views:

1176

answers:

2

I have a drag and drop handler in my Flex application. The drag proxy, or the 'ghost' image to be displayed while dragging, must be loaded before I drag, and that takes some time. How can I make it load immediately or preload? One solution is to duplicate the image, but as far as I know, image objects can't be duplicated without creating another variable, which must still take some time to load.

Perhaps this code will illustrate it better:

public function DragApp (e : MouseEvent) : void {
    var dragInitiator : Image = e.currentTarget as Image;
    var dragSource : DragSource = new DragSource ();

    var dragProxy : Image = new Image ();
    dragProxy.source = e.currentTarget.source; // Won't work unless image is embedded
    dragProxy.load (e.currentTarget.source); // Must load

    setTimeout (DragManager.doDrag, 350, dragInitiator, dragSource, e, dragProxy);
}
+2  A: 

I believe the problem is you aren't setting a width and height for the image (somehow redundant for embedded images):

dragImage:IFlexDisplayObject (default = null) — The image to drag. This argument is optional. If omitted, a standard drag rectangle is used during the drag and drop operation. If you specify an image, you must explicitly set a height and width of the image or else it will not appear.

If you define a width and a height for the Image proxy in your example, it will probably work:

var dragProxy : Image = new Image ();
dragProxy.source = dragInitiator.source;
dragProxy.width = dragInitiator.width;
dragProxy.height = dragInitiator.height;
Stiggler
Thank you! This solves my problem!But why does the image appear when I put the doDrag in a timeout? I thought it had to create another instance of the image and load it first. Does the image set its width and height automatically at some point?
Aethex
+1  A: 

You're better off using a bitmap capture of the image and using that as your dragProxy. Here's some simple code to capture the BitmpData from any UIComponent:

private function getUIComponentBitmapData( target : UIComponent ) : BitmapData
{ 
    var bd : BitmapData = new BitmapData( target.width, target.height );
    var m : Matrix = new Matrix();
    bd.draw( target, m );
    return bd;  
}

Once you have that, you can create a new Bitmap using the BitmapData and supply the Bitmap as the source of an Image component. More details / examples in this blog post:

http://www.cynergysystems.com/blogs/page/andrewtrice?entry=flex_2_bitmapdata_tricks_and

cliff.meyers