Flex/ActionScript - rotate Sprite around its center
Solution 1
The following steps are required to rotate objects based on a reference point (using Matrix object and getBounds):
- Matrix translation (moving to the reference point)
- Matrix rotation
- 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:
Solution 2
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;
}
meiguoren
Updated on July 23, 2022Comments
-
meiguoren almost 2 years
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!
-
Niels over 10 yearsThat is not what was asked for
-
Nande almost 8 yearsit'll be nice to parametrize the deg to rad conversion in case someone (like me) doesn't have it clear. ie: rad_angle = angle*(Math.PI/180) Also, the factor can be cached for speed. Also reusing the matrix works, but i needed to reasign the matrix to the object. (at least on html5 & neko)
-
Nande almost 8 yearsyour example works great, check out my other comment, maybe yours didint work because you needed to reassing the matrix. stackoverflow.com/questions/993445/…