【问题标题】:Flex 4/Air setting bounds for WindowedApplicationWindowedApplication 的 Flex 4/Air 设置边界
【发布时间】:2010-07-09 13:39:02
【问题描述】:

由于某种原因,这个 flex 4 代码给了我一个错误,但我不知道为什么。在我的WindowedApplication 我有:

var prefs:Object = fs.readObject();
fs.close();
var rect:Rectangle = new Rectangle();
rect = prefs.bounds as Rectangle;
this.bounds = rect;  // error here

错误信息: ArgumentError:错误 #2007:参数 rect 必须为非空。

我最初也在没有 rect 对象的情况下尝试过,然后就这样做了:

this.bounds = prefs.bounds as Rectangle;

这给了我以下错误:

TypeError:错误 #1034:类型强制失败:无法将 Object@1dbbe1f1 转换为 flash.geom.Rectangle。

这似乎是一个虚假错误,因为我可以将 pref.bounds 分配给 rect 而不会出错。我不知道为什么这不起作用。它在 flex 3 兼容模式下工作,但这也破坏了我的许多 spark 组件,所以我无法使用它。

【问题讨论】:

    标签: apache-flex air


    【解决方案1】:
    rect = prefs.bounds as Rectangle;
    

    rectnull 结尾,因为 prefs.bounds 不是 Rectangle 类的实例。使用 as 关键字强制转换如果失败则返回 null

    只需在调用readObject 后给trace(prefs.bounds); 以查看其中包含的内容。


    更新:

    prefs.bounds 中的值具有 x、y、width 和 height 属性这一事实并不能使其成为 Rectangle 对象 - 它只是具有这四个属性的对象。简单的解决方案是从这些值创建一个 Rectangle 对象并使用它:

    var prefs:Object = fs.readObject();
    var rect:Rectangle = new Rectangle(prefs.bounds.x, prefs.bounds.y, prefs.width, prefs.height);
    this.bounds = rect;
    

    如果在将矩形对象写入文件流之前调用registerClassAliasreadObject 将返回适当类型的对象,而不是通用对象。

    registerClassAlias("flash.geom.Rectangle", Rectangle);
    fs.writeObject(this.bounds);
    
    //later...
    //Casting with () will throw an error if the read object is not a Rectangle
    var rect:Rectangle = Rectangle(fs.readObject());
    trace(rect);
    

    【讨论】:

    • 所以你是说:this.bounds = rect;等同于:this.bounds = null; windowedApp 不接受吗?当我使用调试器时,prefs.bound 具有您期望的所有字段,宽度、高度、x、y 等。所以如果它不是一个 Rectangle,我不知道它会是什么。顺便说一句,prefs 对象实际上最初是从 this.bounds 生成并保存到文件中的。这就是为什么当我用这段代码读回它时,我很惊讶它会像这样窒息。
    • 您好,感谢您的好评。不幸的是,代码不起作用。 var rect:Rectangle = Rectangle(fs.readObject());跟踪(矩形);给我错误:TypeError: Error #1034: Type Coercion failed: cannot convert Object@1db7bdf9 to flash.geom.Rectangle。即使我使用: registerClassAlias("flash.geom.Rectangle", Rectangle); fs.writeObject(this.bounds);最初保存它。我只是不明白为什么 AIR 不能进行这种 1:1 的转换。这段代码实际上取自 Flex 3 中的一个应用程序,它在那里运行良好。我只是不知道 Flex 4 发生了什么变化。
    • 嘿嘿,其实我又试了一次,果然成功了!我缺少的是 init() 方法中的这一行: flash.net.registerClassAlias("flash.geom.Rectangle", flash.geom.Rectangle);我认为把它放在那里意味着它对 WRITE 和 READ 操作都有效。感谢您的帮助!
    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多