Flex/ActionScript - 围绕其中心旋转Sprite

mei*_*ren 14 apache-flex flash actionscript-3

我在Actionscript中创建了一个Sprite并将其渲染为Flex Canvas.假设:

var fooShape:Sprite = new FooSpriteSubclass();

fooCanvas.rawChildren.addChild(myshape);

//Sprite shape renders on screen

fooShape.rotation = fooNumber;
Run Code Online (Sandbox Code Playgroud)

这将旋转我的形状,但似乎围绕其父容器(画布)的左上角旋转它.

如何强制Sprite绕自己的中心点旋转?我显然可以编写代码来计算旋转,然后让它重新渲染,但我认为必须有一个内置的方法来做到这一点,当然不希望"重新发明轮子",如果可能的话.

我使用的是FlexBuilder,因此无法访问完整的Flash API.

非常感谢!

Ron*_*iew 11

基于参考点旋转对象需要以下步骤(使用Matrix对象和getBounds):

  1. 矩阵转换(移动到参考点)
  2. 矩阵旋转
  3. 矩阵翻译(回到原始位置)


例如,将对象围绕其中心旋转90度:

// 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)); 
Run Code Online (Sandbox Code Playgroud)



使用的关键方法:


iro*_*mer 5

其他例子没有太多运气.这个对我有用.我在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;
Run Code Online (Sandbox Code Playgroud)

}


Bri*_*dge -1

如果您想围绕中心旋转,只需将内部资源 x 和 y 设置为资源宽度和高度的一半,即可将资源置于精灵内部的中心。这将使您的内容居中并允许其围绕中心点旋转。

运行时加载资源的示例如下:

var loader:Loader = new Loader():
var request:URLRequest = new URLRequest(path/to/asset.ext);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onLoaderComplete);
loader.load(request);

private function _onLoaderComplete(e:Event):void
{
    var mc:MovieClip = e.target.content as MovieClip;
    mc.x = -mc.width * 0.5;
    mc.y = -mc.height * 0.5;
    mc.rotation = 90;
    addChild(mc);
}
Run Code Online (Sandbox Code Playgroud)