2011-05-13 67 views
0

嘿家伙,我需要在我正在处理的Flash项目中显示消息。消息需要以屏幕为中心,并且只能使用代码创建。显示文本中心屏幕

通常我可以在上面放一个动态文本框并隐藏它,但是我不能这次。

感谢, 最大

回答

3

我会创建一个具有内它为中心的文本框类。然后在需要显示消息并将其添加到舞台上时创建一个新实例。这是非常简单的例子:

package 
{ 
    import flash.display.Sprite; 
    import flash.text.TextField; 
    import flash.text.TextFieldAutoSize; 

    public class Message extends Sprite { 

      private var tf:TextField; 
      private var s:Sprite; 

      public function Message(msg:String) { 
       s = new Sprite(); 
       s.graphics.beginFill(0,0); 
       s.graphics.drawRect(0,0,800,600); 
       s.graphics.endFill(); 
       addChild(s); 

       tf = new TextField(); 
       tf.autoSize = TextFieldAutoSize.CENTER; 
       tf.width = 400; 
       tf.text = msg; 
       tf.x = (s.width-tf.textWidth)*0.5; 
       tf.y = (s.height-tf.textHeight)*0.5; 
       addChild(tf); 
      } 
    } 
} 

我会添加其他功能,这一点,甚至添加一个调整大小监听器以它为中心。您也可以添加几个按钮来关闭消息。添加精灵只会禁用消息下的任何鼠标点击。这有帮助吗?

+1

实际上关于上面的代码,除了如果自动调整大小on on center,你只需要将x/y放到stage.stageWidth * .5和stage.stageHeight * .5而不需要设置width属性文本字段,或将其设置为0.然后,在执行这些转换之后,设置text属性。这将完美地居中。唯一需要做的小调整就是将textField.textHeight * .5添加到文本字段的y属性中,以使文本正好居中居中。 – 2011-05-13 15:35:36

+1

对不起,忘了提及“800x600”长方形应该是舞台的宽度和高度。我没有把stage.stageWidth等的唯一原因是,从这个类的构造函数中,stage还不存在。您可以通过参数传递宽度/高度,或添加“ADDED_TO_STAGE”事件侦听器,然后根据舞台宽度/高度调整大小。再次,这是一个非常简化的类,但是@Ascension Systems指出,您可以使用自动调整中心来使字段居中。 – Corey 2011-05-13 15:44:16

1

在Flash中动态定位内容非常简单;属性stage.stageWidth和stage.stageHeight可用于确定Flash Player画布的大小。附加到displayList的所有DisplayObject都可以访问stage属性;唯一的问题是该属性在构造函数中将为null,因为它不会被添加到displayList中;但是,我们可以很容易地解决与事件监听器:

public class AutoStageCenterSprite extends Sprite 
{ 
    public function AutoStageCenterSprite() 
    { 
     if (stage == null) { 
      // Wait to be added to Stage before we activate the Resize Listener. 
      addEventListener(Event.ADDED_TO_STAGE, onAddedToStageEvent); 
     } 
     else { 
      centerOnStage(); 
     } 
    } 

    private function onAddedToStageEvent(event : Event) : void 
    { 
     // Now we've been added we can center ourselves... 
     centerOnStage(); 

     // We will also register for Resize Events so we can update our position 
     // is the Stage dimensions change. 
     stage.addEventListener(Event.RESIZE, onResizeEvent); 
    } 

    private function centerOnStage() : void 
    { 
     x = (stage.stageWidth/2) - (width/2); 
     y = (stage.stageHeight/2) - (height/2); 
    } 

    private function onResizeEvent(event : Event) : void 
    { 
     // This event listener will be tripped each the Stage is resized. 
     if (stage != null) { 
      centerOnStage(); 
     } 
    } 
} 

与如何将文本字段添加到您的公式问题涉及的一个部分。 The Flash TextField API。您可以选择扩展TextField类并添加居中代码;或者使用组合来代替,并在您的AutoStageCenterSprite内部创建一个新的TextField实例。