无论长度如何都集中文本标签?

时间:2013-05-26 11:29:50

标签: actionscript-3 flash

是否有一种集中文本标签的方法,以便无论文本长度如何都始终在中心?文本标签显示了Facebook个人资料中的人名,但较短的名称使文本看起来偏离中心。我要集中的例子:

public var nameFormat = new TextFormat("Arial Rounded MT Bold", 28, 0xFFFFFF, null, null, null, null, TextFormatAlign.CENTER);

var PHPvariablespassedin:Object = LoaderInfo(this.root.loaderInfo).parameters;
nameText.defaultTextFormat = myFormat;
nameText.text = String(PHPvariablespassedin['username']);
interfaceLayer.addChild(nameText);
nameText.x = 186;
nameText.y = 80;
nameText.width = 750;
nameText.wordWrap = true;
nameText.selectable = false;
nameText.embedFonts = true;
nameText.antiAliasType = AntiAliasType.ADVANCED;
nameText.setTextFormat(nameFormat);

谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个解决方案,我认为它最适合您的情况(通过TextFormat.align属性的中心文本,用于固定宽度*文本字段的高度):

    var tf:TextField = new TextField();
    //this is by default is NONE, but we must be sure
    tf.autoSize = TextFieldAutoSize.NONE;

    //the main idea set align property to TextFormatAlign.CENTER
    var format:TextFormat = new TextFormat("Arial", 12, 0x000000, null, null, null, null, null, TextFormatAlign.CENTER);

    //set size to fit the format size (this may be already done in flash IDE for example in your skin)
    tf.height = 22;
    tf.width = 100;
    tf.defaultTextFormat = format;
    tf.text = "small";

答案 1 :(得分:0)

您需要有一个背景对象(可以是透明的),它是您希望TextField在其中居中的大小。让我们假设这些事情:

  • 您的MC左上方有一个注册点
  • 背景对象位于0
  • 舞台上有一个TextField,实例名称为textField

然后,您可以将其应用为MovieClip的基类

public class CenteredTextt extends Sprite {

   public var textField:TextField;//will be populated by Flash from the stage
   protected var _text:String;

   public function get text():String {
      return _text;
   }
   public function set text(value:String):void {
      if (textField) {
          textField.defaultFormat = textField.getTextFormat();//may want to move this to a constructor, since it only needs to be done once
          textField.autoSize = TextFieldAutoSize.LEFT;
          textField.htmlText = text;
          textField.x = width/2 - textField.width/2;
          textField.y = height/2 - textField.height/2;
      }
   }
}