[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值。
- import flash.events.MouseEvent;
- import flash.geom.Rectangle;
- // Define the initial viewable area of the TextField instance:
- // left: 0, top: 0, width: TextField's width, height: 350 pixels.
- bigText.scrollRect = new Rectangle(0, 0, bigText.width, 350);
- // Cache the TextField as a bitmap to improve performance.
- bigText.cacheAsBitmap = true;
- // called when the "up" button is clicked
- function scrollUp(event:MouseEvent):void
- {
- // Get access to the current scroll rectangle.
- var rect:Rectangle = bigText.scrollRect;
- // Decrease the y value of the rectangle by 20, effectively
- // shifting the rectangle down by 20 pixels.
- rect.y -= 20;
- // Reassign the rectangle to the TextField to "apply" the change.
- bigText.scrollRect = rect;
- }
- // called when the "down" button is clicked
- function scrollDown(event:MouseEvent):void
- {
- // Get access to the current scroll rectangle.
- var rect:Rectangle = bigText.scrollRect;
- // Increase the y value of the rectangle by 20, effectively
- // shifting the rectangle up by 20 pixels.
- rect.y += 20;
- // Reassign the rectangle to the TextField to "apply" the change.
- bigText.scrollRect = rect;
- }
- up.addEventListener(MouseEvent.CLICK, scrollUp);
- down.addEventListener(MouseEvent.CLICK, scrollDown);
正如本例子所演示的那样,当使用scrollRect属性时,最好使用cacheAsBitmap属性缓存display对象的内容为位图。这样做的好处是,FlashPlayer不用每当display对象被滚动时就要重绘一遍整个display对象,而是把缓存的位图直接填充到适当的位置。

Leave a Reply