I am working on WriteableBitmaps and I have a method that:
- Copies
WriteableBitmapfrom parameter to variable that is outside method - Works on first bitmap
- Adds copied bitmap to
UndoStack
The point of this method is to make changes on bitmap and after that add to undo stack bitmap before changes.
If this method is called very often it causes OutOfMemoryException.
Variables
private WriteableBitmap _oldBitmap;
private Image _oldImage;
Method
public Layer ExecuteTool(Layer layer, Coordinates startingCoords, Color color,int toolSize, ToolType tool)
{
if (toolSize < 1) return null;
Layer cLayer = layer;
_oldBitmap = new WriteableBitmap(layer.LayerBitmap);
_oldImage = layer.LayerImage;
_oldImage.Source = _oldBitmap;
switch (tool)
{
case ToolType.Pen:
cLayer.LayerBitmap = DrawPixel(cLayer.LayerBitmap, startingCoords, toolSize,color);
break;
case ToolType.Bucket:
cLayer.LayerBitmap = FloodFill(cLayer.LayerBitmap, startingCoords, color);
break;
case ToolType.Line:
if (_toolIsExecuting == false)
{
LineAsync(cLayer, startingCoords, color, toolSize);
}
break;
case ToolType.Circle:
if(_toolIsExecuting == false)
{
CircleAsync(cLayer, startingCoords, color);
}
break;
case ToolType.Rectangle:
if(_toolIsExecuting == false)
{
RectangleAsync(cLayer, startingCoords, color);
}
break;
case ToolType.Earser:
cLayer.LayerBitmap = DrawPixel(cLayer.LayerBitmap, startingCoords, toolSize, Colors.Transparent);
break;
case ToolType.Lighten:
if(Mouse.LeftButton == MouseButtonState.Pressed)
{
cLayer.LayerBitmap = Lighten(cLayer.LayerBitmap, startingCoords);
}
else if(Mouse.RightButton == MouseButtonState.Pressed)
{
cLayer.LayerBitmap = Darken(cLayer.LayerBitmap, startingCoords);
}
break;
default:
break;
}
if (tool != ToolType.ColorPicker)
{
UndoManager.RecordChanges("ActiveLayer", new Layer(_oldBitmap, _oldImage), cLayer, string.Format("{0} Tool.", tool.ToString()));
}
return cLayer;
}
PS. It doesn't work without copying bitmap