2009-03-16 15 views

Respuesta

2

a que significa que el índice?

Siguiendo los comentarios, puede hacer una implementación rápida como la siguiente. Esto no es exactamente lo que quiere ya que no puede establecer diferentes alineaciones para cada niño. sólo que no quiero que sea demasiado complicado, es más como 'trabajo de pseudo-código' para darle una idea ...

package 
{ 
    import flash.display.DisplayObject; 
    import flash.display.Sprite;  


    public class SpriteWithRegistration extends Sprite 
    { 

     private var _regV:String = "T"; 
     private var _regH:String = "L"; 

     private var _width:Number = 0; 
     private var _height:Number = 0; 


     public function SpriteWithRegistration(width:Number, height:Number, registrationPoint:String = "TL") 
     { 
      this.width = height; 
      this.height = width; 
      this.registrationPoint = registrationPoint; 
     } 

     public function set registrationPoint(p:String):void 
     { 
      if(p.length != 2) return; 

      var regV:String = p.toUpperCase().substr(0, 1); 
      var regH:String = p.toUpperCase().substr(1, 1); 

      _regV = (regV == "T" || regV == "C" || regV == "B") ? regV : _regV; 
      _regH = (regH == "L" || regH == "C" || regH == "R") ? regH : _regH; 

      alignChildren(); 
     } 

     override public function addChild(child:DisplayObject):DisplayObject 
     { 
      alignChild(child); 
      super.addChild(child); 
      return child; 
     } 

     override public function set width(value:Number):void 
     { 
      _width = value; 
      alignChildren(); 
     } 

     override public function get width():Number 
     { 
      return _width; 
     } 

     override public function set height(value:Number):void 
     { 
      _height = value; 
      alignChildren(); 
     } 

     override public function get height():Number 
     { 
      return _height; 
     } 

     private function alignChildren():void 
     { 
      for(var index:int = 0;index < numChildren; index++) 
       alignChild(getChildAt(index)); 
     } 

     private function alignChild(disp:*):void 
     { 
      switch(_regH) 
      { 
       case "L": disp.x = 0;        break; 
       case "C": disp.x = _width*.5 - disp.width * .5; break; 
       case "R": disp.x = _width - disp.width;   break; 
      } 

      switch(_regV) 
      { 
       case "T": disp.y = 0;        break; 
       case "C": disp.y = _height*.5 - disp.height * .5; break; 
       case "B": disp.y = _height - disp.height;   break; 
      } 
     } 
    } 
} 
+0

no, el punto de registro. por defecto es la parte superior, izquierda. – Ronn

+0

Por cierto, no hay una implementación predeterminada para eso para sprites y formas. Lo cual tiene sentido ya que dependerá totalmente del tamaño de su objeto. Lo mejor es usar un marco de interfaz de usuario o construir uno propio. La idea es especificar el tamaño del soporte y las alineaciones de los niños. –

0

Dependiendo de qué lo necesita, podría ser resuelto por usando DisplayObject. transform. matrix, que devuelve un objeto Matrix.

Por ejemplo, si quiere cambiar el punto de rotación, puede usar la matriz de la transformación para hacer eso.

11

La API de Flash Player no expone esto. Creo que esto se debe a que Flash realmente hornea el punto de registro en los datos de forma cuando crea el SWF. Por lo tanto, no hay un punto de registro real para moverse (en cambio, movería los datos de forma ... ¡si Flash Player le permite editar datos de forma!).

Siempre resuelvo esto simplemente criando mi sprite/forma en otro DisplayObject. Por lo tanto, si tengo spriteA y desea establecer su punto de registro a (15, 35), me gustaría hacer esto:


var spriteB:Sprite = new Sprite(); 
spriteB.addChild(spriteA); 
spriteA.x = 15; 
spriteA.y = 35; 

Y a continuación, a partir de entonces se refiere a spriteB todas partes me refería anteriormente a spriteA.

+1

Esta es definitivamente la forma más fácil y simple. No es el más elegante. Bu, si la sobrecarga de tener un contenedor extra no es un problema ... –

5

Usando la matriz de transformación esto es posible. Aquí hay una buena implementación de esto se encuentra en this site.

public function setRegistrationPoint(s:Sprite, regx:Number, regy:Number, showRegistration:Boolean) 
{ 
    //translate movieclip 
    s.transform.matrix = new Matrix(1, 0, 0, 1, -regx, -regy); 

    //registration point. 
    if (showRegistration) 
    { 
     var mark:Sprite = new Sprite(); 
     mark.graphics.lineStyle(1, 0x000000); 
     mark.graphics.moveTo(-5, -5); 
     mark.graphics.lineTo(5, 5); 
     mark.graphics.moveTo(-5, 5); 
     mark.graphics.lineTo(5, -5); 
     s.parent.addChild(mark); 
    } 
} 
+1

¿Puede explicar esto más detalladamente, por favor? – Vishnu

+0

El enlace está muerto. Quizás explicarlo mejor fue algo bueno de hacer. –

1

Espero que esto ayude a alguien. El framework Starling tiene un método fantástico llamado, "alignPivot()". Tomé su concepto y lo adapté a Flash DisplayList. Básicamente le dices a un sprite que cambie su registro a la izquierda, derecha, centro, arriba y abajo. Este código coloca tu sprite en un sprite contenedor y se posiciona de manera apropiada. Devuelve el sprite contenedor con el sprite original contenido en el interior.

Código almacenado en una llamada llamada llamada, "Posición".

public static function alignPivot(s:DisplayObject, horizontalAlign: String = "center", verticalAlign: String = "center", showRegistration: Boolean = false, _color: uint = 0x000000): Sprite { 

     //create a container sprite to house the sprite you'd like to move 
     var _container: Sprite = new Sprite(); 
     //add your sprite to the continer sprite (the container sprite is what will be returned) 
     _container.addChild(s); 
     //using getBounds(), find the x,y,width,and height of your sprite within the continer. 
     var bounds:Rectangle = _container.getBounds(s); 
     //create variables for x and y cooridnates 
     var xVal: Number; 
     var yVal: Number; 

     //I have a separate class called Align which contains public static constants for positiong. 
     //Check the values passed above and get the correct x value; 
     if (horizontalAlign == Align.LEFT) xVal = -bounds.x; 
     else if (horizontalAlign == Align.CENTER) xVal = -bounds.x - bounds.width * .5; 
     else if (horizontalAlign == Align.RIGHT) xVal = -bounds.x - bounds.width; 
     else throw new ArgumentError("Invalid horizontal alignment: " + horizontalAlign); 

     //Check the values passed above and get the correct y value; 
     if (verticalAlign == Align.TOP) yVal = -bounds.y; 
     else if (verticalAlign == Align.CENTER) yVal = -bounds.y - bounds.height * .5; 
     else if (verticalAlign == Align.BOTTOM) yVal = -bounds.y - bounds.height; 
     else throw new ArgumentError("Invalid vertical alignment: " + verticalAlign); 

     //apply the new x and y cooridnates to your sprite (the one moving within the container we created above) 
     s.x = xVal; 
     s.y = yVal; 

     //optional - this will create a small X at the 0,0 position of the container. 
     //This is helpful if you want to see where your registration points are 
     if (showRegistration) { 
      var mark: Sprite = new Sprite(); 
      mark.graphics.lineStyle(1, _color); 
      mark.graphics.moveTo(-5, -5); 
      mark.graphics.lineTo(5, 5); 
      mark.graphics.moveTo(-5, 5); 
      mark.graphics.lineTo(5, -5); 
      _container.addChild(mark); 
     } 
     //return your contianer sprite 
     //This will replace the sprite that you passed in the first parameter. 
     //That sprite is inside the container, so you won't notice 
     return _container; 


    } 

Implementación:

//Create your sprite 
     var _holder: Sprite = new Sprite(); 
    //Create a shape to put in your sprite 
     var my_shape: Shape = new Shape(); 
     my_shape.graphics.beginFill(0x000000); 
     my_shape.graphics.drawRect(0, 0, 200, 100); 
     my_shape.graphics.endFill(); 
    //Add the shape to your sprite 
     _holder.addChild(my_shape); 
    //Align the holder (must be done AFTER all children have been added) 
    //This will put the registration point at the top-center of the sprite. 
    //_holder is replaced by a sprite (container) that contains _holder. 
    //The _holder inside the container is positioned appropriately. 
    _holder = Position.alignPivot(_holder,Align.CENTER, Align.TOP); 
    //Add the new sprite to your stage. 
    this.addChild(_holder); 

lista de constantes por lo que no tiene que escribirlos usted mismo:

public static const CENTER:String = "center"; 
    public static const LEFT:String = "left"; 
    public static const RIGHT:String = "right"; 
    public static const TOP:String = "top"; 
    public static const BOTTOM:String = "bottom"; 
Cuestiones relacionadas