Friday, March 1, 2013

AS3 : Setting the Mouse Cursor

Sometimes it can be difficult to use custom cursors in AS3.

The Mouse singleton class makes this really easy and fluid. If you compare a side-by-side of a SWF using the old techniques vs the Mouse singleton class, you will notice the difference.

Example: Setting the cursor to an image.

// Embed a graphic for the custom cursor
private var DrawCursor:Class;

// Setup the cursorData object
private var cursorData:MouseCursorData = new MouseCursorData();

// First we setup a vector to handle the bitmapdata objects (you would use more than 1 if you wanted an animated cursor).
var drawCursorData:Vector.<BitmapData> = new Vector.<BitmapData>();
// Now we need to get the bitmap from our embedded graphic
var drawCursor:Bitmap = new DrawCursor();
// now populate the bitmapdata vector with our graphic bitmap data
drawCursorData[0] = drawCursor.bitmapData;
// the default line-up with your cursor's pointer is 0,0 - but if you need to adjust it, you can set the hotSpot to a new x,y
cursorData.hotSpot = new Point(2,12)
// set the cursordata to contain the bitmapdata vector = drawCursorData;
// register the cursor so you can use it later
Mouse.registerCursor("drawCursor", cursorData);

// When you're ready, set the mouse cursor using the cursor property to the registered name.
Mouse.cursor = "drawCursor";

// And when you're all done, you can restore the cursor back using the static property of the MouseCursor class
Mouse.cursor = MouseCursor.AUTO;

Note: There are several default cursors available in the MouseCursor class like Arrow, Button, Hand, and IBeam.

Good Luck!

No comments: