Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex/ActionScript - rotate Sprite around its center

I have created a Sprite in Actionscript and rendered it to a Flex Canvas. Suppose:

var fooShape:Sprite = new FooSpriteSubclass();

fooCanvas.rawChildren.addChild(myshape);

//Sprite shape renders on screen

fooShape.rotation = fooNumber;

This will rotate my shape, but seems to rotate it around the upper-left point of its parent container(the canvas).

How can I force the Sprite to rotate about is own center point? I could obviously write code to calculate the rotation, and then have it re-render, but I think there must be a built-in way to do this, and certainly do not want to 'reinvent the wheel' if possible.

I am using FlexBuilder, and therefore do not have access to the full Flash API.

Thank you much!

like image 695
meiguoren Avatar asked Jun 14 '09 18:06

meiguoren


2 Answers

The following steps are required to rotate objects based on a reference point (using Matrix object and getBounds):

  1. Matrix translation (moving to the reference point)
  2. Matrix rotation
  3. Matrix translation (back to original position)


For example to rotate an object 90 degrees around its center:

// Get the matrix of the object  
var matrix:Matrix = myObject.transform.matrix; 

// Get the rect of the object (to know the dimension) 
var rect:Rectangle = myObject.getBounds(parentOfMyObject); 

// Translating the desired reference point (in this case, center)
matrix.translate(- (rect.left + (rect.width/2)), - (rect.top + (rect.height/2))); 

// Rotation (note: the parameter is in radian) 
matrix.rotate((90/180)*Math.PI); 

// Translating the object back to the original position.
matrix.translate(rect.left + (rect.width/2), rect.top + (rect.height/2)); 



Key methods used:

  • Matrix.rotate
  • Matrix.translate
  • DisplayObject.getBounds
like image 147
Ronnie Liew Avatar answered Nov 12 '22 06:11

Ronnie Liew


Didn't have much luck with the other examples. This one worked for me. I used it on a UIComponent.

http://www.selikoff.net/2010/03/17/solution-to-flex-image-rotation-and-flipping-around-center/

private static function rotateImage(image:Image, degrees:Number):void {
// Calculate rotation and offsets
var radians:Number = degrees * (Math.PI / 180.0);
var offsetWidth:Number = image.contentWidth/2.0;
var offsetHeight:Number =  image.contentHeight/2.0;

// Perform rotation
var matrix:Matrix = new Matrix();
matrix.translate(-offsetWidth, -offsetHeight);
matrix.rotate(radians);
matrix.translate(+offsetWidth, +offsetHeight);
matrix.concat(image.transform.matrix);
image.transform.matrix = matrix;

}

like image 5
irongamer Avatar answered Nov 12 '22 04:11

irongamer