I Love China

技术·人生

技术服务生活
繁體
6月 4th, 2007

[as3][翻译]在设定区域内显示display对象并滚动

上下移动或左右滚动display对象
如果一个display对象比你想让它显示的尺寸大,可以使用scrollRect属性定义这个display对象的可见区域。另外,通过改变scrollRect属性的值来响应用户的动作,可以控制内容左右移动或者上下滚动。

scrollRect属性是Rectangle类的一个实例,Rectangle类把定义一个矩形区域所需要的数据绑定在一个对象中。要定义display对象的可见区域,首先创建一个Rectangle实例,然后把它赋给display对象的scrollRect属性。接下来,把scrollRect属性读到一个单独的Rectangle变量中,通过改变目标属性值就可以左右移动或上下滚动了(比如,改变这个Rectangle实例的x值来左右移动,或者改变y值来上下滚动)。然后再把这个Rectangle实例赋值给scrollRect属性,通知display对象改变它的值。

比如,下面的代码中名为bigText的文本对象太大,而不能在SWF文件边界内显示,因此给它定义一个可见区域。当up和down按钮被点击的时候,它们调用一个函数上下滚动这个文本实例,该函数是会修改文本实例的scrollRect的y值。

ActionScript Code:
  1. import flash.events.MouseEvent;
  2. import flash.geom.Rectangle;
  3.  
  4. // Define the initial viewable area of the TextField instance:
  5. // left: 0, top: 0, width: TextField's width, height: 350 pixels.
  6. bigText.scrollRect = new Rectangle(0, 0, bigText.width, 350);
  7.  
  8. // Cache the TextField as a bitmap to improve performance.
  9. bigText.cacheAsBitmap = true;
  10.  
  11. // called when the "up" button is clicked
  12. function scrollUp(event:MouseEvent):void
  13. {
  14.     // Get access to the current scroll rectangle.
  15.     var rect:Rectangle = bigText.scrollRect;
  16.     // Decrease the y value of the rectangle by 20, effectively
  17.     // shifting the rectangle down by 20 pixels.
  18.     rect.y -= 20;
  19.     // Reassign the rectangle to the TextField to "apply" the change.
  20.     bigText.scrollRect = rect;
  21. }
  22.  
  23. // called when the "down" button is clicked
  24. function scrollDown(event:MouseEvent):void
  25. {
  26.     // Get access to the current scroll rectangle.
  27.     var rect:Rectangle = bigText.scrollRect;
  28.     // Increase the y value of the rectangle by 20, effectively
  29.     // shifting the rectangle up by 20 pixels.
  30.     rect.y += 20;
  31.     // Reassign the rectangle to the TextField to "apply" the change.
  32.     bigText.scrollRect = rect;
  33. }
  34.  
  35. up.addEventListener(MouseEvent.CLICK, scrollUp);
  36. down.addEventListener(MouseEvent.CLICK, scrollDown);

正如本例子所演示的那样,当使用scrollRect属性时,最好使用cacheAsBitmap属性缓存display对象的内容为位图。这样做的好处是,FlashPlayer不用每当display对象被滚动时就要重绘一遍整个display对象,而是把缓存的位图直接填充到适当的位置。

随机文章:

Leave a Reply