有没有人有一个很好的解决方案来在 AS3 中创建一个基于 BitmapData 的滚动器,它可以在向左和向右滚动时环绕图像(并且还支持任意速度,而不仅仅是每个循环一个像素)?我正在尝试编写一个可能只使用 BitmapData.copyPixels() 和 BitmapData.scroll() 的快速且轻量级的滚动条。
到目前为止,我想出了这段代码:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.ui.Keyboard;
[SWF(width="800", height="480", frameRate="60", backgroundColor="#000000")]
public class Main extends Sprite
{
private var _source:BitmapData;
private var _sourceWidth:int;
private var _buffer:BitmapData;
private var _canvas:BitmapData;
private var _rect:Rectangle = new Rectangle();
private var _point:Point = new Point();
private var _xOffset:int = 0;
public function Main()
{
_source = new Picture();
_sourceWidth = _source.width;
_rect.width = _source.width;
_rect.height = _source.height;
_canvas = new BitmapData(_source.width, _source.height, false, 0x000000);
_canvas.copyPixels(_source, _rect, _point);
_buffer = _canvas.clone();
var b:Bitmap = new Bitmap(_canvas);
b.x = stage.stageWidth / 2 - _canvas.width / 2;
b.y = 10;
addChild(b);
stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.RIGHT) scroll(10);
else if (e.keyCode == Keyboard.LEFT) scroll(-10);
});
}
private function scroll(speed:int):void
{
/* Update offset. */
_xOffset -= speed;
/* Reset rect & point. */
_rect.width = _sourceWidth;
_rect.x = 0;
_point.x = 0;
/* Reached the end of the source image width. Copy full source onto buffer. */
if (_xOffset == (speed > -1 ? -(_sourceWidth + speed) : _sourceWidth - speed))
{
_xOffset = -speed;
_buffer.copyPixels(_source, _rect, _point);
}
/* Scroll the buffer by <speed> pixels. */
_buffer.scroll(-speed, 0);
/* Draw the scroll buffer onto the canvas. */
_canvas.copyPixels(_buffer, _rect, _point);
/* Update rect and point for copying scroll-in part. */
_rect.width = Math.abs(_xOffset);
/* Scrolls to left. */
if (speed > -1)
{
_rect.x = 0;
_point.x = _sourceWidth + _xOffset;
}
/* Scrolls to right. */
else
{
_rect.x = _sourceWidth - _xOffset;
_point.x = 0;
}
trace("rect.x: " + _rect.x + " point.x: " + _point.x);
/* Copy the scrolling-in part from source to the canvas. */
_canvas.copyPixels(_source, _rect, _point);
}
}
}
您可以使用光标键向左/向右滚动。仅当图像环绕一次时,滚动才能正常工作。如果决定在其间某处向相反方向滚动,它将弄乱坐标以从滚动缓冲区复制区域。基本上这里的这个块需要工作:
/* Update rect and point for copying scroll-in part. */
_rect.width = Math.abs(_xOffset);
/* Scrolls to left. */
if (speed > -1)
{
_rect.x = 0;
_point.x = _sourceWidth + _xOffset;
}
/* Scrolls to right. */
else
{
_rect.x = _sourceWidth - _xOffset;
_point.x = 0;
}
... rect.x 和 point.x 需要根据滚动方向在此处进行不同的设置,但我不知道如何在不完全过度复杂化整个循环的情况下进行设置。欢迎任何关于更好实施的提示或想法!