清除绘制的最后一个图形?(撤消/重做绘图)


public function drag(e:MouseEvent)
    {
        lineDraw(mouseX, mouseY);
        e.updateAfterEvent();
    }
    public function lineDraw(X:int, Y:int):void
    {
        currentX = X;
        currentY = Y;
        graphics.lineStyle(size, color)
        graphics.moveTo(previousX, previousY)
        graphics.lineTo(currentX, currentY)
        previousX = currentX;
        previousY = currentY;
    }

制作的非常简单的代码,允许我用鼠标画线。函数拖动在MOUSE_DOWNMOUSE_MOVE触发。

我的问题是:我将如何清除绘制的最后一条线?基本上,一个ctrl+z/undo函数,可以根据需要重复多次。

我是否必须完全重写我的代码并将绘制的每一行推送到数组中,然后在数组中向后工作,在单击"撤消"时删除行?还是有其他更好、更简单的解决方案?

谢谢! :)

下面是一个示例: 有关说明,请参阅代码注释

private var undoStates:Vector.<Shape> = new Vector.<Shape>(); //holds all your undo states (HAS TO BE SHAPE SINCE AS3 DOESN"T LET YOU ISNTANTIATE A GRAPHICS OBJECT DIRECTLY)
private var redoStates:Vector.<Shape> = new Vector.<Shape>(); //holds all your redo states
private var undoLevels:int = 1; //how many undo levels you'd like to have
private var redoLevels:int = 1;
public function undo() {
    if (undoStates.length > 0) {  //make sure there is an undo state before preceeding
        //add redo state
        redoStates.push(getState());
        //if redo states are more than redoLevels, remove the oldest one
        if (redoStates.length > redoLevels) redoStates.splice(0, 1);
        //make the the last undo state the current graphics
        graphics.clear(); //not sure if this line is required, can't recall if copyFrom clears first
        graphics.copyFrom(undoStates.pop().graphics); //pop removes the last item from the array and returns it
    }
}
public function redo() {
    if (redoStates.length > 0) {
        //add undo state
        addUndo();
        //make the the last undo state the current graphics
        graphics.clear(); //not sure if copy from (the next line) clears or not
        graphics.copyFrom(redoStates.pop().graphics);
    }
}
private function getState():Shape{
    var state:Shape = new Shape();
    state.graphics.copyFrom(graphics);  //copy the current graphics into a new Graphics object
    return state;
}
private function addUndo():void {
    undoStates.push(getState()); //add the current state to the undo array
    //if more undo states than undoLevels, remove the oldest one
    if (undoStates.length > undoLevels) undoStates.splice(0, 1);
}
public function lineDraw(X:int, Y:int):void {
    currentX = X;
    currentY = Y;

    //create undo state before we draw more
    addUndo();
    graphics.lineStyle(size, color)
    graphics.moveTo(previousX, previousY)
    graphics.lineTo(currentX, currentY)

    previousX = currentX;
    previousY = currentY;
}

最新更新