123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- using PaintDotNet.Measurement.HistoryMementos;
- using System;
- using System.Drawing;
- namespace PaintDotNet.Measurement.HistoryFunctions
- {
- /// <summary>
- /// Crops the image to the currently selected region.
- /// </summary>
- public sealed class CropToSelectionFunction : HistoryFunction
- {
- public static string StaticName
- {
- get
- {
- return PdnResources.GetString("CropAction.Name");
- }
- }
- public override HistoryMemento OnExecute(IDocumentWorkspace historyWorkspace)
- {
- if (historyWorkspace.GetSelection().IsEmpty)
- {
- return null;
- }
- else
- {
- PdnRegion selectionRegion = historyWorkspace.GetSelection().CreateRegion();
- if (selectionRegion.GetArea() == 0)
- {
- selectionRegion.Dispose();
- return null;
- }
- SelectionHistoryMemento sha = new SelectionHistoryMemento(StaticName, null, historyWorkspace);
- ReplaceDocumentHistoryMemento rdha = new ReplaceDocumentHistoryMemento(StaticName, null, historyWorkspace);
- Rectangle boundingBox;
- Rectangle[] inverseRegionRects = null;
- boundingBox = Utility.GetRegionBounds(selectionRegion);
- using (PdnRegion inverseRegion = new PdnRegion(boundingBox))
- {
- inverseRegion.Exclude(selectionRegion);
- inverseRegionRects = Utility.TranslateRectangles(
- inverseRegion.GetRegionScansReadOnlyInt(),
- -boundingBox.X,
- -boundingBox.Y);
- }
- selectionRegion.Dispose();
- selectionRegion = null;
- Document oldDocument = historyWorkspace.GetDocument(); // TODO: serialize this to disk so we don't *have* to store the full thing
- Document newDocument = new Document(boundingBox.Width, boundingBox.Height);
- // copy the document's meta data over
- newDocument.ReplaceMetaDataFrom(oldDocument);
- foreach (Layer layer in oldDocument.Layers)
- {
- if (layer is BitmapLayer)
- {
- BitmapLayer oldLayer = (BitmapLayer)layer;
- Surface croppedSurface = oldLayer.Surface.CreateWindow(boundingBox);
- BitmapLayer newLayer = new BitmapLayer(croppedSurface);
- ColorBgra clearWhite = ColorBgra.White.NewAlpha(0);
- foreach (Rectangle rect in inverseRegionRects)
- {
- newLayer.Surface.Clear(rect, clearWhite);
- }
- newLayer.LoadProperties(oldLayer.SaveProperties());
- newDocument.Layers.Add(newLayer);
- }
- else
- {
- throw new InvalidOperationException("Crop does not support Layers that are not BitmapLayers");
- }
- }
- CompoundHistoryMemento cha = new CompoundHistoryMemento(
- StaticName,
- PdnResources.GetImageResource("Icons.MenuImageCropIcon.png"),
- new HistoryMemento[] { sha, rdha });
- EnterCriticalRegion();
- historyWorkspace.SetDocument(newDocument);
- return cha;
- }
- }
- public CropToSelectionFunction()
- : base(PaintDotNet.Measurement.Enum.ActionFlags.None)
- {
- }
- }
- }
|