【问题标题】:Declaring Stage in external class function and using it in other class?在外部类函数中声明阶段并在其他类中使用它?
【发布时间】:2012-10-26 13:24:48
【问题描述】:

我想要实现的是制作一个“centerItem”方法,使您的对象在舞台上居中。我想在我的 Misc 类文件中添加这个方法,并在我的应用程序的任何地方使用它。我已经像下面这样尝试过,但这没有用:

public static function centerItem(item:*):void
{
    item.x = (stage.stageWidth - item.width) >> 1;
    item.y = (stage.stageHeight - item.height) >> 1;
}

并这样称呼它:

Misc.centerItem(myObjectToPlaceOnStage);

但是当我尝试它时,它只会给我一个错误。我已经在网上看了,但我没有找到任何建设性的解决方案。我希望有人能找到解决方案/破解

【问题讨论】:

    标签: actionscript-3 positioning stage


    【解决方案1】:

    如果您的对象已经添加到舞台上,您可以访问其舞台属性:

    public static function centerItem(item:DisplayObject):void
    {
        item.x = (item.stage.stageWidth - item.width) >> 1;
        item.y = (item.stage.stageHeight - item.height) >> 1;
    }
    

    顺便说一句,我已将您的项目参数输入到DisplayObject,因此您确定它具有widthheightstage 属性。

    【讨论】:

    • if(item.hasOwnProperty("stage")) { item.x = (item.stage.stageWidth - item.width) >> 1; item.y = (item.stage.stageHeight - item.height) >> 1; } 添加了 hasProperty,100% 确定它已添加到阶段(我不确定这是否是正确的方法,但好的,仍然感谢 ^^)
    • 没有。不要使用 addOwnProperty,它会有属性。您可以使用item.stage != null 来检查它是否在舞台上。
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2012-04-26
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    相关资源
    最近更新 更多