diff --git a/Greenshot/Drawing/CropContainer.cs b/Greenshot/Drawing/CropContainer.cs index a9363ec86..8adcf1ef7 100644 --- a/Greenshot/Drawing/CropContainer.cs +++ b/Greenshot/Drawing/CropContainer.cs @@ -68,7 +68,7 @@ namespace Greenshot.Drawing { } } - public override bool hasContextMenu { + public override bool HasContextMenu { get { // No context menu for the CropContainer return false; diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index 82d0e178f..68e5c74a4 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -43,10 +43,10 @@ namespace Greenshot.Drawing { /// OnPropertyChanged whenever a public property has been changed. /// [Serializable] - public abstract class DrawableContainer : AbstractFieldHolderWithChildren, INotifyPropertyChanged, IDrawableContainer { + public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer { private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); - protected static readonly EditorConfiguration editorConfig = IniConfig.GetIniSection(); - private bool _isMadeUndoable = false; + protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); + private bool _isMadeUndoable; protected EditStatus _defaultEditMode = EditStatus.DRAWING; public EditStatus DefaultEditMode { @@ -61,20 +61,22 @@ namespace Greenshot.Drawing { } protected virtual void Dispose(bool disposing) { - if (disposing) { - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - if (_grippers[i] != null) { - _grippers[i].Dispose(); - _grippers[i] = null; - } - } - _grippers = null; - } - - FieldAggregator aggProps = _parent.FieldAggregator; - aggProps.UnbindElement(this); + if (!disposing) { + return; } + if (_grippers != null) { + for (int i = 0; i < _grippers.Length; i++) { + if (_grippers[i] == null) { + continue; + } + _grippers[i].Dispose(); + _grippers[i] = null; + } + _grippers = null; + } + + FieldAggregator aggProps = _parent.FieldAggregator; + aggProps.UnbindElement(this); } ~DrawableContainer() { @@ -82,10 +84,10 @@ namespace Greenshot.Drawing { } [NonSerialized] - private PropertyChangedEventHandler propertyChanged; + private PropertyChangedEventHandler _propertyChanged; public event PropertyChangedEventHandler PropertyChanged { - add { propertyChanged += value; } - remove{ propertyChanged -= value; } + add { _propertyChanged += value; } + remove{ _propertyChanged -= value; } } public List Filters { @@ -108,7 +110,7 @@ namespace Greenshot.Drawing { } [NonSerialized] protected Gripper[] _grippers; - private bool layoutSuspended = false; + private bool _layoutSuspended; [NonSerialized] private Gripper _targetGripper; @@ -120,7 +122,7 @@ namespace Greenshot.Drawing { } [NonSerialized] - private bool _selected = false; + private bool _selected; public bool Selected { get {return _selected;} set { @@ -141,47 +143,51 @@ namespace Greenshot.Drawing { } - private int _left = 0; + private int _left; public int Left { get { return _left; } set { - if(value != _left) { - _left = value; - DoLayout(); + if (value == _left) { + return; } + _left = value; + DoLayout(); } } - private int _top = 0; + private int _top; public int Top { get { return _top; } set { - if(value != _top) { - _top = value; - DoLayout(); + if (value == _top) { + return; } + _top = value; + DoLayout(); } } - private int _width = 0; + private int _width; public int Width { get { return _width; } set { - if(value != _width) { - _width = value; - DoLayout(); + if (value == _width) { + return; } + _width = value; + DoLayout(); } } - private int _height = 0; + private int _height; public int Height { get { return _height; } set { - if(value != _height) { - _height = value; - DoLayout(); + if (value == _height) { + return; } + _height = value; + DoLayout(); } } @@ -189,46 +195,50 @@ namespace Greenshot.Drawing { get { return new Point(_left, _top); } + set { + _left = value.X; + _top = value.Y; + } } public Size Size { get { return new Size(_width, _height); } + set { + _width = value.Width; + _height = value.Height; + } } [NonSerialized] - /// - /// will store current bounds of this DrawableContainer before starting a resize - /// + // will store current bounds of this DrawableContainer before starting a resize private Rectangle _boundsBeforeResize = Rectangle.Empty; [NonSerialized] - /// - /// "workbench" rectangle - used for calculatoing bounds during resizing (to be applied to this DrawableContainer afterwards) - /// + // "workbench" rectangle - used for calculatoing bounds during resizing (to be applied to this DrawableContainer afterwards) private RectangleF _boundsAfterResize = RectangleF.Empty; public Rectangle Bounds { get { return GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); } set { - Left = round(value.Left); - Top = round(value.Top); - Width = round(value.Width); - Height = round(value.Height); + Left = Round(value.Left); + Top = Round(value.Top); + Width = Round(value.Width); + Height = Round(value.Height); } } public virtual void ApplyBounds(RectangleF newBounds) { - Left = round(newBounds.Left); - Top = round(newBounds.Top); - Width = round(newBounds.Width); - Height = round(newBounds.Height); + Left = Round(newBounds.Left); + Top = Round(newBounds.Top); + Width = Round(newBounds.Width); + Height = Round(newBounds.Height); } public DrawableContainer(Surface parent) { InitializeFields(); - this._parent = parent; + _parent = parent; InitControls(); } @@ -240,19 +250,13 @@ namespace Greenshot.Drawing { RemoveChild(filter); } - private int round(float f) { + private static int Round(float f) { if(float.IsPositiveInfinity(f) || f>int.MaxValue/2) return int.MaxValue/2; if (float.IsNegativeInfinity(f) || fint.MaxValue/2) return int.MaxValue/2; - if (Double.IsNegativeInfinity(d) || d 0; @@ -648,7 +637,9 @@ namespace Greenshot.Drawing { InitControls(); } _parent = newParent; - _parent.Controls.AddRange(_grippers); + if (_grippers != null) { + _parent.Controls.AddRange(_grippers); + } foreach(IFilter filter in Filters) { filter.Parent = this; } @@ -657,9 +648,9 @@ namespace Greenshot.Drawing { // drawablecontainers are regarded equal if they are of the same type and their bounds are equal. this should be sufficient. public override bool Equals(object obj) { bool ret = false; - if (obj != null && GetType().Equals(obj.GetType())) { + if (obj != null && GetType() == obj.GetType()) { DrawableContainer other = obj as DrawableContainer; - if (_left==other._left && _top==other._top && _width==other._width && _height==other._height) { + if (other != null && _left==other._left && _top==other._top && _width==other._width && _height==other._height) { ret = true; } } @@ -671,8 +662,8 @@ namespace Greenshot.Drawing { } protected void OnPropertyChanged(string propertyName) { - if (propertyChanged != null) { - propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + if (_propertyChanged != null) { + _propertyChanged(this, new PropertyChangedEventArgs(propertyName)); Invalidate(); } } @@ -696,7 +687,7 @@ namespace Greenshot.Drawing { public void HandleFieldChanged(object sender, FieldChangedEventArgs e) { LOG.DebugFormat("Field {0} changed", e.Field.FieldType); if (e.Field.FieldType == FieldType.SHADOW) { - accountForShadowChange = true; + _accountForShadowChange = true; } Invalidate(); } @@ -712,11 +703,19 @@ namespace Greenshot.Drawing { return; } Point center = new Point(Left + (Width/2), Top + (Height/2)); - Point[] points = { center }; + Point[] points; + if (TargetGripper != null) { + points = new[] {center, TargetGripper.Location}; + + } else { + points = new[] { center}; + } matrix.TransformPoints(points); - Left = points[0].X - (Width / 2); - Top = points[0].Y - (Height / 2); + Location = new Point(points[0].X - (Width/2), points[0].Y - (Height/2)); + if (TargetGripper != null) { + TargetGripper.Location = points[1]; + } } public virtual void Rotate(RotateFlipType rotateFlipType) { @@ -778,13 +777,13 @@ namespace Greenshot.Drawing { return ScaleHelper.ShapeAngleRoundBehavior.Instance; } - public virtual bool hasContextMenu { + public virtual bool HasContextMenu { get { return true; } } - public virtual bool hasDefaultSize { + public virtual bool HasDefaultSize { get { return false; } diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 7b0070034..76360296a 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -509,7 +509,7 @@ namespace Greenshot.Drawing { bool canReset = false; foreach (var drawableContainer in this) { var container = (DrawableContainer) drawableContainer; - if (container.hasDefaultSize) { + if (container.HasDefaultSize) { canReset = true; } } @@ -519,7 +519,7 @@ namespace Greenshot.Drawing { item.Click += delegate { foreach (var drawableContainer in this) { var container = (DrawableContainer) drawableContainer; - if (!container.hasDefaultSize) { + if (!container.HasDefaultSize) { continue; } Size defaultSize = container.DefaultSize; @@ -538,7 +538,7 @@ namespace Greenshot.Drawing { bool hasMenu = false; foreach (var drawableContainer in this) { var container = (DrawableContainer) drawableContainer; - if (!container.hasContextMenu) { + if (!container.HasContextMenu) { continue; } hasMenu = true; diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index 2b5fde975..119b79f30 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -58,7 +58,8 @@ namespace Greenshot.Drawing { protected override void InitializeFields() { AddField(GetType(), FieldType.LINE_THICKNESS, 3); AddField(GetType(), FieldType.LINE_COLOR, Color.Red); - } + } + protected void Init() { if (_grippers != null) { @@ -108,10 +109,10 @@ namespace Greenshot.Drawing { public override bool HandleMouseMove(int mouseX, int mouseY) { Point previousPoint = capturePoints[capturePoints.Count-1]; - if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2*editorConfig.FreehandSensitivity)) { + if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2*EditorConfig.FreehandSensitivity)) { capturePoints.Add(new Point(mouseX, mouseY)); } - if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= editorConfig.FreehandSensitivity) { + if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { //path.AddCurve(new Point[]{lastMouse, new Point(mouseX, mouseY)}); freehandPath.AddLine(lastMouse, new Point(mouseX, mouseY)); lastMouse = new Point(mouseX, mouseY); @@ -127,7 +128,7 @@ namespace Greenshot.Drawing { /// public override void HandleMouseUp(int mouseX, int mouseY) { // Make sure we don't loose the ending point - if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= editorConfig.FreehandSensitivity) { + if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { capturePoints.Add(new Point(mouseX, mouseY)); } RecalculatePath(); diff --git a/Greenshot/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index eb6e1e93a..7985acaad 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -87,7 +87,7 @@ namespace Greenshot.Drawing { } } - public override bool hasDefaultSize { + public override bool HasDefaultSize { get { return true; } diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index 26aadc9da..7b48fe2cd 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -197,7 +197,7 @@ namespace Greenshot.Drawing { } } - public override bool hasDefaultSize { + public override bool HasDefaultSize { get { return true; } diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 20ddc8248..338a918d1 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -50,17 +50,17 @@ namespace Greenshot.Drawing { private static CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID - private Guid uniqueID = Guid.NewGuid(); + private Guid _uniqueId = Guid.NewGuid(); /// /// The GUID of the surface /// public Guid ID { get { - return uniqueID; + return _uniqueId; } set { - uniqueID = value; + _uniqueId = value; } } @@ -68,43 +68,43 @@ namespace Greenshot.Drawing { /// Event handlers (do not serialize!) /// [NonSerialized] - private SurfaceElementEventHandler movingElementChanged; + private SurfaceElementEventHandler _movingElementChanged; public event SurfaceElementEventHandler MovingElementChanged { add { - movingElementChanged += value; + _movingElementChanged += value; } remove { - movingElementChanged -= value; + _movingElementChanged -= value; } } [NonSerialized] - private SurfaceDrawingModeEventHandler drawingModeChanged; + private SurfaceDrawingModeEventHandler _drawingModeChanged; public event SurfaceDrawingModeEventHandler DrawingModeChanged { add { - drawingModeChanged += value; + _drawingModeChanged += value; } remove { - drawingModeChanged -= value; + _drawingModeChanged -= value; } } [NonSerialized] - private SurfaceSizeChangeEventHandler surfaceSizeChanged; + private SurfaceSizeChangeEventHandler _surfaceSizeChanged; public event SurfaceSizeChangeEventHandler SurfaceSizeChanged { add { - surfaceSizeChanged += value; + _surfaceSizeChanged += value; } remove { - surfaceSizeChanged -= value; + _surfaceSizeChanged -= value; } } [NonSerialized] - private SurfaceMessageEventHandler surfaceMessage; + private SurfaceMessageEventHandler _surfaceMessage; public event SurfaceMessageEventHandler SurfaceMessage { add { - surfaceMessage += value; + _surfaceMessage += value; } remove { - surfaceMessage -= value; + _surfaceMessage -= value; } } @@ -112,63 +112,57 @@ namespace Greenshot.Drawing { /// inUndoRedo makes sure we don't undo/redo while in a undo/redo action /// [NonSerialized] - private bool inUndoRedo = false; + private bool _inUndoRedo; /// /// Make only one surfacemove cycle undoable, see SurfaceMouseMove /// [NonSerialized] - private bool isSurfaceMoveMadeUndoable = false; + private bool _isSurfaceMoveMadeUndoable; /// /// Undo/Redo stacks, should not be serialized as the file would be way to big /// [NonSerialized] - private Stack undoStack = new Stack(); + private readonly Stack _undoStack = new Stack(); [NonSerialized] - private Stack redoStack = new Stack(); + private readonly Stack _redoStack = new Stack(); /// /// Last save location, do not serialize! /// [NonSerialized] - private string lastSaveFullPath = null; + private string _lastSaveFullPath; /// /// current drawing mode, do not serialize! /// [NonSerialized] - private DrawingModes drawingMode = DrawingModes.None; + private DrawingModes _drawingMode = DrawingModes.None; /// /// the keyslocked flag helps with focus issues /// [NonSerialized] - private bool keysLocked = false; + private bool _keysLocked; /// /// Location of the mouse-down (it "starts" here), do not serialize /// [NonSerialized] - private Point mouseStart = Point.Empty; + private Point _mouseStart = Point.Empty; /// /// are we in a mouse down, do not serialize /// [NonSerialized] - private bool mouseDown = false; - - /// - /// are we dragging, do not serialize - /// - [NonSerialized] - private bool draggingInProgress = false; + private bool _mouseDown; /// /// The selected element for the mouse down, do not serialize /// [NonSerialized] - private IDrawableContainer mouseDownElement = null; + private IDrawableContainer _mouseDownElement; /// /// all selected elements, do not serialize @@ -180,25 +174,25 @@ namespace Greenshot.Drawing { /// the element we are drawing with, do not serialize /// [NonSerialized] - private IDrawableContainer drawingElement = null; + private IDrawableContainer _drawingElement; /// /// the element we want to draw with (not yet drawn), do not serialize /// [NonSerialized] - private IDrawableContainer undrawnElement = null; + private IDrawableContainer _undrawnElement; /// /// the cropcontainer, when cropping this is set, do not serialize /// [NonSerialized] - private IDrawableContainer cropContainer = null; + private IDrawableContainer _cropContainer; /// /// the brush which is used for transparent backgrounds, set by the editor, do not serialize /// [NonSerialized] - private Brush transparencyBackgroundBrush; + private Brush _transparencyBackgroundBrush; /// /// The buffer is only for drawing on it when using filters (to supply access) @@ -208,7 +202,7 @@ namespace Greenshot.Drawing { /// TODO: Check if this buffer is still needed! /// [NonSerialized] - private Bitmap buffer = null; + private Bitmap _buffer; /// /// all stepLabels for the surface, needed with serialization @@ -229,7 +223,8 @@ namespace Greenshot.Drawing { /// number of steplabels before the supplied container public int CountStepLabels(IDrawableContainer stopAtContainer) { int number = 1; - foreach (StepLabelContainer possibleThis in _stepLabels) { + foreach (var drawableContainer in _stepLabels) { + var possibleThis = (StepLabelContainer) drawableContainer; if (possibleThis == stopAtContainer) { break; } @@ -243,22 +238,22 @@ namespace Greenshot.Drawing { /// /// all elements on the surface, needed with serialization /// - private DrawableContainerList elements; + private readonly DrawableContainerList _elements; /// /// all elements on the surface, needed with serialization /// - private FieldAggregator fieldAggregator = new FieldAggregator(); + private FieldAggregator _fieldAggregator = new FieldAggregator(); /// /// the cursor container, needed with serialization as we need a direct acces to it. /// - private IDrawableContainer cursorContainer = null; + private IDrawableContainer _cursorContainer; /// /// the capture details, needed with serialization /// - private ICaptureDetails captureDetails = null; + private ICaptureDetails _captureDetails; /// /// the modified flag specifies if the surface has had modifications after the last export. @@ -266,19 +261,19 @@ namespace Greenshot.Drawing { /// After serialization this should actually be "false" (the surface came from a stream) /// For now we just serialize it... /// - private bool modified = true; + private bool _modified = true; /// /// The image is the actual captured image, needed with serialization /// - private Image image = null; + private Image _image; public Image Image { get { - return image; + return _image; } set { - image = value; - Size = image.Size; + _image = value; + Size = _image.Size; } } @@ -288,10 +283,10 @@ namespace Greenshot.Drawing { /// public FieldAggregator FieldAggregator { get { - return fieldAggregator; + return _fieldAggregator; } set { - fieldAggregator = value; + _fieldAggregator = value; } } @@ -300,7 +295,7 @@ namespace Greenshot.Drawing { /// public IDrawableContainer CursorContainer { get { - return cursorContainer; + return _cursorContainer; } } @@ -309,7 +304,7 @@ namespace Greenshot.Drawing { /// public bool HasCursor { get { - return cursorContainer != null; + return _cursorContainer != null; } } @@ -317,8 +312,8 @@ namespace Greenshot.Drawing { /// A simple helper method to remove the cursor from the surface /// public void RemoveCursor() { - RemoveElement(cursorContainer, true); - cursorContainer = null; + RemoveElement(_cursorContainer, true); + _cursorContainer = null; } /// @@ -326,10 +321,10 @@ namespace Greenshot.Drawing { /// public Brush TransparencyBackgroundBrush { get { - return transparencyBackgroundBrush; + return _transparencyBackgroundBrush; } set { - transparencyBackgroundBrush = value; + _transparencyBackgroundBrush = value; } } @@ -338,10 +333,10 @@ namespace Greenshot.Drawing { /// public bool KeysLocked { get { - return keysLocked; + return _keysLocked; } set { - keysLocked = value; + _keysLocked = value; } } @@ -350,10 +345,10 @@ namespace Greenshot.Drawing { /// public bool Modified { get { - return modified; + return _modified; } set { - modified = value; + _modified = value; } } @@ -361,13 +356,13 @@ namespace Greenshot.Drawing { /// The DrawingMode property specifies the mode for drawing, more or less the element type. /// public DrawingModes DrawingMode { - get {return drawingMode;} + get {return _drawingMode;} set { - drawingMode = value; - if (drawingModeChanged != null) { + _drawingMode = value; + if (_drawingModeChanged != null) { SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs(); - eventArgs.DrawingMode = drawingMode; - drawingModeChanged.Invoke(this, eventArgs); + eventArgs.DrawingMode = _drawingMode; + _drawingModeChanged.Invoke(this, eventArgs); } DeselectAllElements(); CreateUndrawnElement(); @@ -379,10 +374,10 @@ namespace Greenshot.Drawing { /// public string LastSaveFullPath { get { - return lastSaveFullPath; + return _lastSaveFullPath; } set { - lastSaveFullPath = value; + _lastSaveFullPath = value; } } @@ -399,10 +394,10 @@ namespace Greenshot.Drawing { /// public ICaptureDetails CaptureDetails { get { - return captureDetails; + return _captureDetails; } set { - captureDetails = value; + _captureDetails = value; } } @@ -411,8 +406,8 @@ namespace Greenshot.Drawing { /// public Surface() : base(){ Count++; - elements = new DrawableContainerList(uniqueID); - selectedElements = new DrawableContainerList(uniqueID); + _elements = new DrawableContainerList(_uniqueId); + selectedElements = new DrawableContainerList(_uniqueId); LOG.Debug("Creating surface!"); MouseDown += SurfaceMouseDown; MouseUp += SurfaceMouseUp; @@ -424,7 +419,7 @@ namespace Greenshot.Drawing { DragEnter += OnDragEnter; // bind selected & elements to this, otherwise they can't inform of modifications selectedElements.Parent = this; - elements.Parent = this; + _elements.Parent = this; // Make sure we are visible Visible = true; TabStop = false; @@ -436,19 +431,19 @@ namespace Greenshot.Drawing { /// /// Private method, the current image is disposed the new one will stay. /// - /// The new image + /// The new image /// true if the old image needs to be disposed, when using undo this should not be true!! private void SetImage(Image newImage, bool dispose) { // Dispose - if (image != null && dispose) { - image.Dispose(); + if (_image != null && dispose) { + _image.Dispose(); } // Set new values Image = newImage; Size = newImage.Size; - modified = true; + _modified = true; } /// @@ -471,46 +466,46 @@ namespace Greenshot.Drawing { Rectangle captureRect = new Rectangle(Point.Empty, capture.Image.Size); // check if cursor is on the capture, otherwise we leave it out. if (cursorRect.IntersectsWith(captureRect)) { - cursorContainer = AddIconContainer(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y); - SelectElement(cursorContainer); + _cursorContainer = AddIconContainer(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y); + SelectElement(_cursorContainer); } } // Make sure the image is NOT disposed, we took the reference directly into ourselves ((Capture)capture).NullImage(); - captureDetails = capture.CaptureDetails; + _captureDetails = capture.CaptureDetails; } protected override void Dispose(bool disposing) { if (disposing) { Count--; LOG.Debug("Disposing surface!"); - if (buffer != null) { - buffer.Dispose(); - buffer = null; + if (_buffer != null) { + _buffer.Dispose(); + _buffer = null; } - if (transparencyBackgroundBrush != null) { - transparencyBackgroundBrush.Dispose(); - transparencyBackgroundBrush = null; + if (_transparencyBackgroundBrush != null) { + _transparencyBackgroundBrush.Dispose(); + _transparencyBackgroundBrush = null; } // Cleanup undo/redo stacks - while (undoStack != null && undoStack.Count > 0) { - undoStack.Pop().Dispose(); + while (_undoStack != null && _undoStack.Count > 0) { + _undoStack.Pop().Dispose(); } - while (redoStack != null && redoStack.Count > 0) { - redoStack.Pop().Dispose(); + while (_redoStack != null && _redoStack.Count > 0) { + _redoStack.Pop().Dispose(); } - foreach (IDrawableContainer container in elements) { + foreach (IDrawableContainer container in _elements) { container.Dispose(); } - if (undrawnElement != null) { - undrawnElement.Dispose(); - undrawnElement = null; + if (_undrawnElement != null) { + _undrawnElement.Dispose(); + _undrawnElement = null; } - if (cropContainer != null) { - cropContainer.Dispose(); - cropContainer = null; + if (_cropContainer != null) { + _cropContainer.Dispose(); + _cropContainer = null; } } base.Dispose(disposing); @@ -520,11 +515,11 @@ namespace Greenshot.Drawing { /// Undo the last action /// public void Undo() { - if (undoStack.Count > 0) { - inUndoRedo = true; - IMemento top = undoStack.Pop(); - redoStack.Push(top.Restore()); - inUndoRedo = false; + if (_undoStack.Count > 0) { + _inUndoRedo = true; + IMemento top = _undoStack.Pop(); + _redoStack.Push(top.Restore()); + _inUndoRedo = false; } } @@ -532,11 +527,11 @@ namespace Greenshot.Drawing { /// Undo an undo (=redo) /// public void Redo() { - if (redoStack.Count > 0) { - inUndoRedo = true; - IMemento top = redoStack.Pop(); - undoStack.Push(top.Restore()); - inUndoRedo = false; + if (_redoStack.Count > 0) { + _inUndoRedo = true; + IMemento top = _redoStack.Pop(); + _undoStack.Push(top.Restore()); + _inUndoRedo = false; } } @@ -545,7 +540,7 @@ namespace Greenshot.Drawing { /// public bool CanUndo { get { - return undoStack.Count > 0; + return _undoStack.Count > 0; } } @@ -554,7 +549,7 @@ namespace Greenshot.Drawing { /// public bool CanRedo { get { - return redoStack.Count > 0; + return _redoStack.Count > 0; } } @@ -564,7 +559,7 @@ namespace Greenshot.Drawing { public LangKey UndoActionLanguageKey { get { if (CanUndo) { - return undoStack.Peek().ActionLanguageKey; + return _undoStack.Peek().ActionLanguageKey; } return LangKey.none; } @@ -576,7 +571,7 @@ namespace Greenshot.Drawing { public LangKey RedoActionLanguageKey { get { if (CanRedo) { - return redoStack.Peek().ActionLanguageKey; + return _redoStack.Peek().ActionLanguageKey; } return LangKey.none; } @@ -586,22 +581,23 @@ namespace Greenshot.Drawing { /// Make an action undo-able /// /// The memento implementing the undo + /// Allow changes to be merged public void MakeUndoable(IMemento memento, bool allowMerge) { - if (inUndoRedo) { + if (_inUndoRedo) { throw new InvalidOperationException("Invoking do within an undo/redo action."); } if (memento != null) { bool allowPush = true; - if (undoStack.Count > 0 && allowMerge) { + if (_undoStack.Count > 0 && allowMerge) { // Check if merge is possible - allowPush = !undoStack.Peek().Merge(memento); + allowPush = !_undoStack.Peek().Merge(memento); } if (allowPush) { // Clear the redo-stack and dispose - while(redoStack.Count > 0) { - redoStack.Pop().Dispose(); + while(_redoStack.Count > 0) { + _redoStack.Pop().Dispose(); } - undoStack.Push(memento); + _undoStack.Push(memento); } } } @@ -617,7 +613,7 @@ namespace Greenshot.Drawing { try { long lengtBefore = streamWrite.Length; BinaryFormatter binaryWrite = new BinaryFormatter(); - binaryWrite.Serialize(streamWrite, elements); + binaryWrite.Serialize(streamWrite, _elements); bytesWritten = streamWrite.Length - lengtBefore; } catch (Exception e) { LOG.Error("Error serializing elements to stream.", e); @@ -633,13 +629,11 @@ namespace Greenshot.Drawing { try { BinaryFormatter binaryRead = new BinaryFormatter(); DrawableContainerList loadedElements = (DrawableContainerList) binaryRead.Deserialize(streamRead); - if (loadedElements != null) { - loadedElements.Parent = this; - DeselectAllElements(); - AddElements(loadedElements); - SelectElements(loadedElements); - FieldAggregator.BindElements(loadedElements); - } + loadedElements.Parent = this; + DeselectAllElements(); + AddElements(loadedElements); + SelectElements(loadedElements); + FieldAggregator.BindElements(loadedElements); } catch (Exception e) { LOG.Error("Error serializing elements from stream.", e); } @@ -651,53 +645,53 @@ namespace Greenshot.Drawing { /// The element is than used while drawing on the surface. /// private void CreateUndrawnElement() { - if(undrawnElement != null) { - FieldAggregator.UnbindElement(undrawnElement); + if(_undrawnElement != null) { + FieldAggregator.UnbindElement(_undrawnElement); } switch (DrawingMode) { case DrawingModes.Rect: - undrawnElement = new RectangleContainer(this); + _undrawnElement = new RectangleContainer(this); break; case DrawingModes.Ellipse: - undrawnElement = new EllipseContainer(this); + _undrawnElement = new EllipseContainer(this); break; case DrawingModes.Text: - undrawnElement = new TextContainer(this); + _undrawnElement = new TextContainer(this); break; case DrawingModes.SpeechBubble: - undrawnElement = new SpeechbubbleContainer(this); + _undrawnElement = new SpeechbubbleContainer(this); break; case DrawingModes.StepLabel: - undrawnElement = new StepLabelContainer(this); + _undrawnElement = new StepLabelContainer(this); break; case DrawingModes.Line: - undrawnElement = new LineContainer(this); + _undrawnElement = new LineContainer(this); break; case DrawingModes.Arrow: - undrawnElement = new ArrowContainer(this); + _undrawnElement = new ArrowContainer(this); break; case DrawingModes.Highlight: - undrawnElement = new HighlightContainer(this); + _undrawnElement = new HighlightContainer(this); break; case DrawingModes.Obfuscate: - undrawnElement = new ObfuscateContainer(this); + _undrawnElement = new ObfuscateContainer(this); break; case DrawingModes.Crop: - cropContainer = new CropContainer(this); - undrawnElement = cropContainer; + _cropContainer = new CropContainer(this); + _undrawnElement = _cropContainer; break; case DrawingModes.Bitmap: - undrawnElement = new ImageContainer(this); + _undrawnElement = new ImageContainer(this); break; case DrawingModes.Path: - undrawnElement = new FreehandContainer(this); + _undrawnElement = new FreehandContainer(this); break; case DrawingModes.None: - undrawnElement = null; + _undrawnElement = null; break; } - if (undrawnElement != null) { - FieldAggregator.BindElement(undrawnElement); + if (_undrawnElement != null) { + FieldAggregator.BindElement(_undrawnElement); } } @@ -783,7 +777,7 @@ namespace Greenshot.Drawing { LOG.Debug(format); } } - if (draggingInProgress || (e.AllowedEffect & DragDropEffects.Copy) != DragDropEffects.Copy) { + if ((e.AllowedEffect & DragDropEffects.Copy) != DragDropEffects.Copy) { e.Effect=DragDropEffects.None; } else { if (ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits")) { @@ -800,7 +794,6 @@ namespace Greenshot.Drawing { /// /// private void OnDragDrop(object sender, DragEventArgs e) { - List filenames = ClipboardHelper.GetImageFilenames(e.Data); Point mouse = PointToClient(new Point(e.X, e.Y)); if (e.Data.GetDataPresent("Text")) { string possibleUrl = ClipboardHelper.GetText(e.Data); @@ -822,16 +815,6 @@ namespace Greenshot.Drawing { } } -// private void QueryContinueDragDrop(object sender, QueryContinueDragEventArgs e) { -// LOG.Debug("QueryContinueDrag: " + e.Action); -// if (e.EscapePressed) { -// e.Action = DragAction.Cancel; -// } -// } -// -// private void GiveFeedbackDragDrop(object sender, GiveFeedbackEventArgs e) { -// e.UseDefaultCursors = true; -// } #endregion /// @@ -840,23 +823,23 @@ namespace Greenshot.Drawing { /// true if cropped public bool AutoCrop() { Rectangle cropRectangle = ImageHelper.FindAutoCropRectangle(Image, conf.AutoCropDifference); - if (isCropPossible(ref cropRectangle)) { - DeselectAllElements(); - // Maybe a bit obscure, but the following line creates a drop container - // It's available as "undrawnElement" - DrawingMode = DrawingModes.Crop; - undrawnElement.Left = cropRectangle.X; - undrawnElement.Top = cropRectangle.Y; - undrawnElement.Width = cropRectangle.Width; - undrawnElement.Height = cropRectangle.Height; - undrawnElement.Status = EditStatus.UNDRAWN; - AddElement(undrawnElement); - SelectElement(undrawnElement); - drawingElement = null; - undrawnElement = null; - return true; + if (!IsCropPossible(ref cropRectangle)) { + return false; } - return false; + DeselectAllElements(); + // Maybe a bit obscure, but the following line creates a drop container + // It's available as "undrawnElement" + DrawingMode = DrawingModes.Crop; + _undrawnElement.Left = cropRectangle.X; + _undrawnElement.Top = cropRectangle.Y; + _undrawnElement.Width = cropRectangle.Width; + _undrawnElement.Height = cropRectangle.Height; + _undrawnElement.Status = EditStatus.UNDRAWN; + AddElement(_undrawnElement); + SelectElement(_undrawnElement); + _drawingElement = null; + _undrawnElement = null; + return true; } /// @@ -865,7 +848,7 @@ namespace Greenshot.Drawing { /// The color for the background public void Clear(Color newColor) { //create a blank bitmap the same size as original - Bitmap newBitmap = ImageHelper.CreateEmptyLike((Bitmap)Image, Color.Empty); + Bitmap newBitmap = ImageHelper.CreateEmptyLike(Image, Color.Empty); if (newBitmap != null) { // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, null), false); @@ -888,13 +871,13 @@ namespace Greenshot.Drawing { Image newImage = ImageHelper.ApplyEffect(Image, effect, matrix); if (newImage != null) { // Make sure the elements move according to the offset the effect made the bitmap move - elements.Transform(matrix); + _elements.Transform(matrix); // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, matrix), false); SetImage(newImage, false); Invalidate(); - if (surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, newImage.Size))) { - surfaceSizeChanged(this, null); + if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, newImage.Size))) { + _surfaceSizeChanged(this, null); } } } finally { @@ -908,7 +891,7 @@ namespace Greenshot.Drawing { /// /// /// true if this is possible - public bool isCropPossible(ref Rectangle cropRectangle) { + public bool IsCropPossible(ref Rectangle cropRectangle) { cropRectangle = GuiRectangle.GetGuiRectangle(cropRectangle.Left, cropRectangle.Top, cropRectangle.Width, cropRectangle.Height); if (cropRectangle.Left < 0) { cropRectangle = new Rectangle(0, cropRectangle.Top, cropRectangle.Width + cropRectangle.Left, cropRectangle.Height); @@ -935,12 +918,12 @@ namespace Greenshot.Drawing { /// Type of message /// Message itself public void SendMessageEvent(object source, SurfaceMessageTyp messageType, string message) { - if (surfaceMessage != null) { + if (_surfaceMessage != null) { SurfaceMessageEventArgs eventArgs = new SurfaceMessageEventArgs(); eventArgs.Message = message; eventArgs.MessageType = messageType; eventArgs.Surface = this; - surfaceMessage(source, eventArgs); + _surfaceMessage(source, eventArgs); } } @@ -950,7 +933,7 @@ namespace Greenshot.Drawing { /// /// public bool ApplyCrop(Rectangle cropRectangle) { - if (isCropPossible(ref cropRectangle)) { + if (IsCropPossible(ref cropRectangle)) { Rectangle imageRectangle = new Rectangle(Point.Empty, Image.Size); Bitmap tmpImage; // Make sure we have information, this this fails @@ -965,15 +948,15 @@ namespace Greenshot.Drawing { } Matrix matrix = new Matrix(); - matrix.Translate(-cropRectangle.Left, -cropRectangle.Top); + matrix.Translate(-cropRectangle.Left, -cropRectangle.Top, MatrixOrder.Append); // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, matrix), false); // Do not dispose otherwise we can't undo the image! SetImage(tmpImage, false); - elements.Transform(matrix); - if (surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, tmpImage.Size))) { - surfaceSizeChanged(this, null); + _elements.Transform(matrix); + if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, tmpImage.Size))) { + _surfaceSizeChanged(this, null); } Invalidate(); return true; @@ -986,14 +969,14 @@ namespace Greenshot.Drawing { /// This is called from the SurfaceBackgroundChangeMemento. /// /// - /// + /// public void UndoBackgroundChange(Image previous, Matrix matrix) { SetImage(previous, false); if (matrix != null) { - elements.Transform(matrix); + _elements.Transform(matrix); } - if (surfaceSizeChanged != null) { - surfaceSizeChanged(this, null); + if (_surfaceSizeChanged != null) { + _surfaceSizeChanged(this, null); } Invalidate(); } @@ -1004,7 +987,7 @@ namespace Greenshot.Drawing { /// /// void SurfaceMouseDown(object sender, MouseEventArgs e) { - mouseStart = e.Location; + _mouseStart = e.Location; // check contextmenu if (e.Button == MouseButtons.Right) { @@ -1013,7 +996,7 @@ namespace Greenshot.Drawing { selectedList = selectedElements; } else { // Single element - IDrawableContainer rightClickedContainer = elements.ClickableElementAt(mouseStart.X, mouseStart.Y); + IDrawableContainer rightClickedContainer = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); if (rightClickedContainer != null) { selectedList = new DrawableContainerList(ID); selectedList.Add(rightClickedContainer); @@ -1025,43 +1008,43 @@ namespace Greenshot.Drawing { return; } - mouseDown = true; - isSurfaceMoveMadeUndoable = false; + _mouseDown = true; + _isSurfaceMoveMadeUndoable = false; - if (cropContainer != null && ((undrawnElement == null) || (undrawnElement != null && DrawingMode != DrawingModes.Crop))) { - RemoveElement(cropContainer, false); - cropContainer = null; - drawingElement = null; + if (_cropContainer != null && ((_undrawnElement == null) || (_undrawnElement != null && DrawingMode != DrawingModes.Crop))) { + RemoveElement(_cropContainer, false); + _cropContainer = null; + _drawingElement = null; } - if (drawingElement == null && DrawingMode != DrawingModes.None) { - if (undrawnElement == null) { + if (_drawingElement == null && DrawingMode != DrawingModes.None) { + if (_undrawnElement == null) { DeselectAllElements(); - if (undrawnElement == null) { + if (_undrawnElement == null) { CreateUndrawnElement(); } } - drawingElement = undrawnElement; - drawingElement.Status = undrawnElement.DefaultEditMode; - undrawnElement = null; + _drawingElement = _undrawnElement; // if a new element has been drawn, set location and register it - if (drawingElement != null) { - drawingElement.PropertyChanged += ElementPropertyChanged; - if (!drawingElement.HandleMouseDown(mouseStart.X, mouseStart.Y)) { - drawingElement.Left = mouseStart.X; - drawingElement.Top = mouseStart.Y; + if (_drawingElement != null) { + _drawingElement.Status = _undrawnElement.DefaultEditMode; + _drawingElement.PropertyChanged += ElementPropertyChanged; + if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { + _drawingElement.Left = _mouseStart.X; + _drawingElement.Top = _mouseStart.Y; } - AddElement(drawingElement); - drawingElement.Selected = true; + AddElement(_drawingElement); + _drawingElement.Selected = true; } + _undrawnElement = null; } else { // check whether an existing element was clicked // we save mouse down element separately from selectedElements (checked on mouse up), // since it could be moved around before it is actually selected - mouseDownElement = elements.ClickableElementAt(mouseStart.X, mouseStart.Y); + _mouseDownElement = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); - if (mouseDownElement != null) { - mouseDownElement.Status = EditStatus.MOVING; + if (_mouseDownElement != null) { + _mouseDownElement.Status = EditStatus.MOVING; } } } @@ -1074,15 +1057,15 @@ namespace Greenshot.Drawing { void SurfaceMouseUp(object sender, MouseEventArgs e) { Point currentMouse = new Point(e.X, e.Y); - elements.Status = EditStatus.IDLE; - if (mouseDownElement != null) { - mouseDownElement.Status = EditStatus.IDLE; + _elements.Status = EditStatus.IDLE; + if (_mouseDownElement != null) { + _mouseDownElement.Status = EditStatus.IDLE; } - mouseDown = false; - mouseDownElement = null; + _mouseDown = false; + _mouseDownElement = null; if (DrawingMode == DrawingModes.None) { // check whether an existing element was clicked - IDrawableContainer element = elements.ClickableElementAt(currentMouse.X, currentMouse.Y); + IDrawableContainer element = _elements.ClickableElementAt(currentMouse.X, currentMouse.Y); bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; if (element != null) { element.Invalidate(); @@ -1109,21 +1092,21 @@ namespace Greenshot.Drawing { selectedElements.Selected = true; } - if (drawingElement != null) { - if (!drawingElement.InitContent()) { - elements.Remove(drawingElement); - drawingElement.Invalidate(); + if (_drawingElement != null) { + if (!_drawingElement.InitContent()) { + _elements.Remove(_drawingElement); + _drawingElement.Invalidate(); } else { - drawingElement.HandleMouseUp(currentMouse.X, currentMouse.Y); - drawingElement.Invalidate(); - if (Math.Abs(drawingElement.Width) < 5 && Math.Abs(drawingElement.Height) < 5) { - drawingElement.Width = 25; - drawingElement.Height = 25; + _drawingElement.HandleMouseUp(currentMouse.X, currentMouse.Y); + _drawingElement.Invalidate(); + if (Math.Abs(_drawingElement.Width) < 5 && Math.Abs(_drawingElement.Height) < 5) { + _drawingElement.Width = 25; + _drawingElement.Height = 25; } - SelectElement(drawingElement); - drawingElement.Selected = true; + SelectElement(_drawingElement); + _drawingElement.Selected = true; } - drawingElement = null; + _drawingElement = null; } } @@ -1141,34 +1124,34 @@ namespace Greenshot.Drawing { Cursor = Cursors.Default; } - if (mouseDown) { - if (mouseDownElement != null) { // an element is currently dragged - mouseDownElement.Invalidate(); + if (_mouseDown) { + if (_mouseDownElement != null) { // an element is currently dragged + _mouseDownElement.Invalidate(); selectedElements.HideGrippers(); // Move the element - if (mouseDownElement.Selected) { - if (!isSurfaceMoveMadeUndoable) { + if (_mouseDownElement.Selected) { + if (!_isSurfaceMoveMadeUndoable) { // Only allow one undoable per mouse-down/move/up "cycle" - isSurfaceMoveMadeUndoable = true; + _isSurfaceMoveMadeUndoable = true; selectedElements.MakeBoundsChangeUndoable(false); } // dragged element has been selected before -> move all - selectedElements.MoveBy(currentMouse.X - mouseStart.X, currentMouse.Y - mouseStart.Y); + selectedElements.MoveBy(currentMouse.X - _mouseStart.X, currentMouse.Y - _mouseStart.Y); } else { - if (!isSurfaceMoveMadeUndoable) { + if (!_isSurfaceMoveMadeUndoable) { // Only allow one undoable per mouse-down/move/up "cycle" - isSurfaceMoveMadeUndoable = true; - mouseDownElement.MakeBoundsChangeUndoable(false); + _isSurfaceMoveMadeUndoable = true; + _mouseDownElement.MakeBoundsChangeUndoable(false); } // dragged element is not among selected elements -> just move dragged one - mouseDownElement.MoveBy(currentMouse.X - mouseStart.X, currentMouse.Y - mouseStart.Y); + _mouseDownElement.MoveBy(currentMouse.X - _mouseStart.X, currentMouse.Y - _mouseStart.Y); } - mouseStart = currentMouse; - mouseDownElement.Invalidate(); - modified = true; - } else if (drawingElement != null) { - drawingElement.HandleMouseMove(currentMouse.X, currentMouse.Y); - modified = true; + _mouseStart = currentMouse; + _mouseDownElement.Invalidate(); + _modified = true; + } else if (_drawingElement != null) { + _drawingElement.HandleMouseMove(currentMouse.X, currentMouse.Y); + _modified = true; } } } @@ -1190,7 +1173,7 @@ namespace Greenshot.Drawing { /// private Image GetImage(RenderMode renderMode) { // Generate a copy of the original image with a dpi equal to the default... - Bitmap clone = ImageHelper.Clone(image, PixelFormat.DontCare); + Bitmap clone = ImageHelper.Clone(_image, PixelFormat.DontCare); // otherwise we would have a problem drawing the image to the surface... :( using (Graphics graphics = Graphics.FromImage(clone)) { // Do not set the following, the containers need to decide themselves @@ -1198,7 +1181,7 @@ namespace Greenshot.Drawing { //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; //graphics.CompositingQuality = CompositingQuality.HighQuality; //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - elements.Draw(graphics, clone, renderMode, new Rectangle(Point.Empty, clone.Size)); + _elements.Draw(graphics, clone, renderMode, new Rectangle(Point.Empty, clone.Size)); } return clone; } @@ -1224,19 +1207,19 @@ namespace Greenshot.Drawing { return; } - if (elements.HasIntersectingFilters(clipRectangle)) { - if (buffer != null) { - if (buffer.Width != Image.Width || buffer.Height != Image.Height || buffer.PixelFormat != Image.PixelFormat) { - buffer.Dispose(); - buffer = null; + if (_elements.HasIntersectingFilters(clipRectangle)) { + if (_buffer != null) { + if (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat) { + _buffer.Dispose(); + _buffer = null; } } - if (buffer == null) { - buffer = ImageHelper.CreateEmpty(Image.Width, Image.Height, Image.PixelFormat, Color.Empty, Image.HorizontalResolution, Image.VerticalResolution); + if (_buffer == null) { + _buffer = ImageHelper.CreateEmpty(Image.Width, Image.Height, Image.PixelFormat, Color.Empty, Image.HorizontalResolution, Image.VerticalResolution); LOG.DebugFormat("Created buffer with size: {0}x{1}", Image.Width, Image.Height); } // Elements might need the bitmap, so we copy the part we need - using (Graphics graphics = Graphics.FromImage(buffer)) { + using (Graphics graphics = Graphics.FromImage(_buffer)) { // do not set the following, the containers need to decide this themselves! //graphics.SmoothingMode = SmoothingMode.HighQuality; //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; @@ -1244,12 +1227,12 @@ namespace Greenshot.Drawing { //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(Image, clipRectangle, clipRectangle, GraphicsUnit.Pixel); graphics.SetClip(targetGraphics); - elements.Draw(graphics, buffer, RenderMode.EDIT, clipRectangle); + _elements.Draw(graphics, _buffer, RenderMode.EDIT, clipRectangle); } - targetGraphics.DrawImage(buffer, clipRectangle, clipRectangle, GraphicsUnit.Pixel); + targetGraphics.DrawImage(_buffer, clipRectangle, clipRectangle, GraphicsUnit.Pixel); } else { targetGraphics.DrawImage(Image, clipRectangle, clipRectangle, GraphicsUnit.Pixel); - elements.Draw(targetGraphics, null, RenderMode.EDIT, clipRectangle); + _elements.Draw(targetGraphics, null, RenderMode.EDIT, clipRectangle); } } @@ -1259,10 +1242,10 @@ namespace Greenshot.Drawing { /// PaintEventArgs protected override void OnPaintBackground(PaintEventArgs e) { // check if we need to draw the checkerboard - if (Image.IsAlphaPixelFormat(Image.PixelFormat) && transparencyBackgroundBrush != null) { + if (Image.IsAlphaPixelFormat(Image.PixelFormat) && _transparencyBackgroundBrush != null) { Graphics targetGraphics = e.Graphics; Rectangle clipRectangle = e.ClipRectangle; - targetGraphics.FillRectangle(transparencyBackgroundBrush, clipRectangle); + targetGraphics.FillRectangle(_transparencyBackgroundBrush, clipRectangle); } else { Graphics targetGraphics = e.Graphics; targetGraphics.Clear(BackColor); @@ -1284,7 +1267,7 @@ namespace Greenshot.Drawing { /// the new element /// true if the adding should be undoable public void AddElement(IDrawableContainer element, bool makeUndoable) { - elements.Add(element); + _elements.Add(element); DrawableContainer container = element as DrawableContainer; if (container != null) { container.FieldChanged += element_FieldChanged; @@ -1297,7 +1280,7 @@ namespace Greenshot.Drawing { if (makeUndoable) { MakeUndoable(new AddElementMemento(this, element), false); } - modified = true; + _modified = true; } /// @@ -1307,7 +1290,7 @@ namespace Greenshot.Drawing { /// flag specifying if the remove needs to be undoable public void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable) { DeselectElement(elementToRemove); - elements.Remove(elementToRemove); + _elements.Remove(elementToRemove); DrawableContainer element = elementToRemove as DrawableContainer; if (element != null) { element.FieldChanged -= element_FieldChanged; @@ -1318,7 +1301,7 @@ namespace Greenshot.Drawing { if (makeUndoable) { MakeUndoable(new DeleteElementMemento(this, elementToRemove), false); } - modified = true; + _modified = true; } /// @@ -1358,10 +1341,10 @@ namespace Greenshot.Drawing { RemoveElement(element, true); } selectedElements.Clear(); - if (movingElementChanged != null) { + if (_movingElementChanged != null) { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; - movingElementChanged(this, eventArgs); + _movingElementChanged(this, eventArgs); } } } @@ -1394,15 +1377,15 @@ namespace Greenshot.Drawing { // create new collection so that we can iterate safely (selectedElements might change due with confirm/cancel) List selectedDCs = new List(selectedElements); foreach (IDrawableContainer dc in selectedDCs){ - if (dc.Equals(cropContainer)){ + if (dc.Equals(_cropContainer)){ DrawingMode = DrawingModes.None; // No undo memento for the cropcontainer itself, only for the effect - RemoveElement(cropContainer, false); + RemoveElement(_cropContainer, false); if (confirm) { - ApplyCrop(cropContainer.Bounds); + ApplyCrop(_cropContainer.Bounds); } - cropContainer.Dispose(); - cropContainer = null; + _cropContainer.Dispose(); + _cropContainer = null; } } } @@ -1429,7 +1412,7 @@ namespace Greenshot.Drawing { if (dcs != null) { // Make element(s) only move 10,10 if the surface is the same Point moveOffset; - bool isSameSurface = (dcs.ParentID == uniqueID); + bool isSameSurface = (dcs.ParentID == _uniqueId); dcs.Parent = this; if (isSameSurface) { moveOffset = new Point(10, 10); @@ -1541,10 +1524,10 @@ namespace Greenshot.Drawing { container.Selected = false; selectedElements.Remove(container); FieldAggregator.UnbindElement(container); - if (movingElementChanged != null) { + if (_movingElementChanged != null) { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; - movingElementChanged(this, eventArgs); + _movingElementChanged(this, eventArgs); } } @@ -1561,10 +1544,10 @@ namespace Greenshot.Drawing { selectedElements.Remove(element); FieldAggregator.UnbindElement(element); } - if (movingElementChanged != null) { + if (_movingElementChanged != null) { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; - movingElementChanged(this, eventArgs); + _movingElementChanged(this, eventArgs); } } } @@ -1579,10 +1562,10 @@ namespace Greenshot.Drawing { container.ShowGrippers(); container.Selected = true; FieldAggregator.BindElement(container); - if (movingElementChanged != null) { + if (_movingElementChanged != null) { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; - movingElementChanged(this, eventArgs); + _movingElementChanged(this, eventArgs); } container.Invalidate(); } @@ -1592,7 +1575,7 @@ namespace Greenshot.Drawing { /// Select all elements, this is called when Ctrl+A is pressed /// public void SelectAllElements() { - SelectElements(elements); + SelectElements(_elements); } /// @@ -1671,7 +1654,7 @@ namespace Greenshot.Drawing { /// public DrawableContainerList Elements { get { - return elements; + return _elements; } } @@ -1679,32 +1662,32 @@ namespace Greenshot.Drawing { /// pulls selected elements up one level in hierarchy /// public void PullElementsUp() { - elements.PullElementsUp(selectedElements); - elements.Invalidate(); + _elements.PullElementsUp(selectedElements); + _elements.Invalidate(); } /// /// pushes selected elements up to top in hierarchy /// public void PullElementsToTop() { - elements.PullElementsToTop(selectedElements); - elements.Invalidate(); + _elements.PullElementsToTop(selectedElements); + _elements.Invalidate(); } /// /// pushes selected elements down one level in hierarchy /// public void PushElementsDown() { - elements.PushElementsDown(selectedElements); - elements.Invalidate(); + _elements.PushElementsDown(selectedElements); + _elements.Invalidate(); } /// /// pushes selected elements down to bottom in hierarchy /// public void PushElementsToBottom() { - elements.PushElementsToBottom(selectedElements); - elements.Invalidate(); + _elements.PushElementsToBottom(selectedElements); + _elements.Invalidate(); } /// @@ -1712,7 +1695,7 @@ namespace Greenshot.Drawing { /// /// true if selected elements could be pulled up, false otherwise public bool CanPullSelectionUp() { - return elements.CanPullUp(selectedElements); + return _elements.CanPullUp(selectedElements); } /// @@ -1720,7 +1703,7 @@ namespace Greenshot.Drawing { /// /// true if selected elements could be pushed down, false otherwise public bool CanPushSelectionDown() { - return elements.CanPushDown(selectedElements); + return _elements.CanPushDown(selectedElements); } public void ElementPropertyChanged(object sender, PropertyChangedEventArgs e) { @@ -1732,7 +1715,7 @@ namespace Greenshot.Drawing { } public bool IsOnSurface(IDrawableContainer container) { - return elements.Contains(container); + return _elements.Contains(container); } } } diff --git a/GreenshotPlugin/Core/ImageHelper.cs b/GreenshotPlugin/Core/ImageHelper.cs index 3344e1f00..d9892f942 100644 --- a/GreenshotPlugin/Core/ImageHelper.cs +++ b/GreenshotPlugin/Core/ImageHelper.cs @@ -62,9 +62,9 @@ namespace GreenshotPlugin.Core { } try { // Get the index of the orientation property. - int orientation_index = Array.IndexOf(image.PropertyIdList, EXIF_ORIENTATION_ID); + int orientationIndex = Array.IndexOf(image.PropertyIdList, EXIF_ORIENTATION_ID); // If there is no such property, return Unknown. - if (orientation_index < 0) { + if (orientationIndex < 0) { return; } PropertyItem item = image.GetPropertyItem(EXIF_ORIENTATION_ID); @@ -129,18 +129,18 @@ namespace GreenshotPlugin.Core { int srcWidth=image.Width; int srcHeight=image.Height; if (thumbHeight < 0) { - thumbHeight = (int)(thumbWidth * ((float)srcHeight / (float)srcWidth)); + thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth)); } if (thumbWidth < 0) { - thumbWidth = (int)(thumbHeight * ((float)srcWidth / (float)srcHeight)); + thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight)); } if (maxWidth > 0 && thumbWidth > maxWidth) { thumbWidth = Math.Min(thumbWidth, maxWidth); - thumbHeight = (int)(thumbWidth * ((float)srcHeight / (float)srcWidth)); + thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth)); } if (maxHeight > 0 && thumbHeight > maxHeight) { thumbHeight = Math.Min(thumbHeight, maxHeight); - thumbWidth = (int)(thumbHeight * ((float)srcWidth / (float)srcHeight)); + thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight)); } Bitmap bmp = new Bitmap(thumbWidth, thumbHeight); @@ -174,12 +174,13 @@ namespace GreenshotPlugin.Core { LOG.Warn("Can't crop a null/zero size image!"); return false; } - + /// /// Private helper method for the FindAutoCropRectangle /// /// /// + /// /// Rectangle private static Rectangle FindAutoCropRectangle(IFastBitmap fastBitmap, Point colorPoint, int cropDifference) { Rectangle cropRectangle = Rectangle.Empty; @@ -194,24 +195,26 @@ namespace GreenshotPlugin.Core { int diffR = Math.Abs(currentColor.R - referenceColor.R); int diffG = Math.Abs(currentColor.G - referenceColor.G); int diffB = Math.Abs(currentColor.B - referenceColor.B); - if (((diffR + diffG + diffB) / 3) > cropDifference) { - if (x < min.X) min.X = x; - if (y < min.Y) min.Y = y; - if (x > max.X) max.X = x; - if (y > max.Y) max.Y = y; + if (((diffR + diffG + diffB)/3) <= cropDifference) { + continue; } + if (x < min.X) min.X = x; + if (y < min.Y) min.Y = y; + if (x > max.X) max.X = x; + if (y > max.Y) max.Y = y; } } } else { for (int y = 0; y < fastBitmap.Height; y++) { for (int x = 0; x < fastBitmap.Width; x++) { Color currentColor = fastBitmap.GetColorAt(x, y); - if (referenceColor.Equals(currentColor)) { - if (x < min.X) min.X = x; - if (y < min.Y) min.Y = y; - if (x > max.X) max.X = x; - if (y > max.Y) max.Y = y; + if (!referenceColor.Equals(currentColor)) { + continue; } + if (x < min.X) min.X = x; + if (y < min.Y) min.Y = y; + if (x > max.X) max.X = x; + if (y > max.Y) max.Y = y; } } } @@ -228,10 +231,11 @@ namespace GreenshotPlugin.Core { /// Get a rectangle for the image which crops the image of all colors equal to that on 0,0 /// /// + /// /// Rectangle public static Rectangle FindAutoCropRectangle(Image image, int cropDifference) { Rectangle cropRectangle = Rectangle.Empty; - Rectangle currentRectangle = Rectangle.Empty; + Rectangle currentRectangle; List checkPoints = new List(); // Top Left checkPoints.Add(new Point(0, 0)); @@ -391,20 +395,20 @@ namespace GreenshotPlugin.Core { /// /// Get the number of icon in the file /// - /// /// Location of the EXE or DLL /// public static int CountAssociatedIcons(string location) { - IntPtr large = IntPtr.Zero; - IntPtr small = IntPtr.Zero; + IntPtr large; + IntPtr small; return Shell32.ExtractIconEx(location, -1, out large, out small, 0); } /// /// Apply the effect to the bitmap /// - /// Bitmap + /// Bitmap /// IEffect + /// /// Bitmap public static Image ApplyEffect(Image sourceImage, IEffect effect, Matrix matrix) { List effects = new List(); @@ -415,8 +419,9 @@ namespace GreenshotPlugin.Core { /// /// Apply the effects in the supplied order to the bitmap /// - /// Bitmap + /// Bitmap /// List + /// /// Bitmap public static Image ApplyEffects(Image sourceImage, List effects, Matrix matrix) { Image currentImage = sourceImage; @@ -449,8 +454,8 @@ namespace GreenshotPlugin.Core { Image returnImage = CreateEmpty(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using (GraphicsPath path = new GraphicsPath()) { Random random = new Random(); - int HorizontalRegions = (int)(sourceImage.Width / horizontalToothRange); - int VerticalRegions = (int)(sourceImage.Height / verticalToothRange); + int horizontalRegions = sourceImage.Width / horizontalToothRange; + int verticalRegions = sourceImage.Height / verticalToothRange; // Start Point previousEndingPoint = new Point(0,0); @@ -458,8 +463,8 @@ namespace GreenshotPlugin.Core { if (edges[0]) { previousEndingPoint = new Point(horizontalToothRange, random.Next(1, toothHeight)); // Top - for (int i = 0; i < HorizontalRegions; i++) { - int x = (int)previousEndingPoint.X + horizontalToothRange; + for (int i = 0; i < horizontalRegions; i++) { + int x = previousEndingPoint.X + horizontalToothRange; int y = random.Next(1, toothHeight); newEndingPoint = new Point(x, y); path.AddLine(previousEndingPoint, newEndingPoint); @@ -472,9 +477,9 @@ namespace GreenshotPlugin.Core { } if (edges[1]) { // Right - for (int i = 0; i < VerticalRegions; i++) { + for (int i = 0; i < verticalRegions; i++) { int x = sourceImage.Width - random.Next(1, toothHeight); - int y = (int)previousEndingPoint.Y + verticalToothRange; + int y = previousEndingPoint.Y + verticalToothRange; newEndingPoint = new Point(x, y); path.AddLine(previousEndingPoint, newEndingPoint); previousEndingPoint = newEndingPoint; @@ -486,8 +491,8 @@ namespace GreenshotPlugin.Core { } if (edges[2]) { // Bottom - for (int i = 0; i < HorizontalRegions; i++) { - int x = (int)previousEndingPoint.X - horizontalToothRange; + for (int i = 0; i < horizontalRegions; i++) { + int x = previousEndingPoint.X - horizontalToothRange; int y = sourceImage.Height - random.Next(1, toothHeight); newEndingPoint = new Point(x, y); path.AddLine(previousEndingPoint, newEndingPoint); @@ -500,9 +505,9 @@ namespace GreenshotPlugin.Core { } if (edges[3]) { // Left - for (int i = 0; i < VerticalRegions; i++) { + for (int i = 0; i < verticalRegions; i++) { int x = random.Next(1, toothHeight); - int y = (int)previousEndingPoint.Y - verticalToothRange; + int y = previousEndingPoint.Y - verticalToothRange; newEndingPoint = new Point(x, y); path.AddLine(previousEndingPoint, newEndingPoint); previousEndingPoint = newEndingPoint; @@ -510,7 +515,7 @@ namespace GreenshotPlugin.Core { } else { newEndingPoint = new Point(0, 0); path.AddLine(previousEndingPoint, newEndingPoint); - previousEndingPoint = newEndingPoint; + //previousEndingPoint = newEndingPoint; } path.CloseFigure(); @@ -522,7 +527,7 @@ namespace GreenshotPlugin.Core { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; using (Brush brush = new TextureBrush(sourceImage)) { - // Imporant note: If the target wouldn't be at 0,0 we need to translate-transform!! + // Important note: If the target wouldn't be at 0,0 we need to translate-transform!! graphics.FillPath(brush, path); } } @@ -530,24 +535,6 @@ namespace GreenshotPlugin.Core { return returnImage; } - /// - /// Helper Method for the ApplyBlur - /// - /// - /// - private static int[] CreateGaussianBlurRow(int amount) { - int size = 1 + (amount * 2); - int[] weights = new int[size]; - - for (int i = 0; i <= amount; ++i) { - // 1 + aa - aa + 2ai - ii - weights[i] = 16 * (i + 1); - weights[weights.Length - i - 1] = weights[i]; - } - - return weights; - } - /// /// Apply BoxBlur to the destinationBitmap /// @@ -638,7 +625,6 @@ namespace GreenshotPlugin.Core { /// /// BoxBlurHorizontal is a private helper method for the BoxBlur, only for IFastBitmaps with alpha channel /// - /// Source BitmapBuffer /// Target BitmapBuffer /// Range must be odd! private static void BoxBlurHorizontalAlpha(IFastBitmap targetFastBitmap, int range) { @@ -694,11 +680,8 @@ namespace GreenshotPlugin.Core { if (targetFastBitmap.hasAlphaChannel) { throw new NotSupportedException("BoxBlurVertical should NOT be called for bitmaps with alpha channel"); } - int w = targetFastBitmap.Width; int halfRange = range / 2; Color[] newColors = new Color[targetFastBitmap.Height]; - int oldPixelOffset = -(halfRange + 1) * w; - int newPixelOffset = (halfRange) * w; byte[] tmpColor = new byte[4]; for (int x = targetFastBitmap.Left; x < targetFastBitmap.Right; x++) { int hits = 0; @@ -745,11 +728,8 @@ namespace GreenshotPlugin.Core { throw new NotSupportedException("BoxBlurVerticalAlpha should be called for bitmaps with alpha channel"); } - int w = targetFastBitmap.Width; int halfRange = range / 2; Color[] newColors = new Color[targetFastBitmap.Height]; - int oldPixelOffset = -(halfRange + 1) * w; - int newPixelOffset = (halfRange) * w; byte[] tmpColor = new byte[4]; for (int x = targetFastBitmap.Left; x < targetFastBitmap.Right; x++) { int hits = 0; @@ -818,13 +798,14 @@ namespace GreenshotPlugin.Core { /// How dark is the shadow /// Size of the shadow /// What pixel format must the returning bitmap have - /// How many pixels is the original image moved? + /// + /// The transform matrix which describes how the elements need to be transformed to stay at the same location /// Bitmap with the shadow, is bigger than the sourceBitmap!! public static Bitmap CreateShadow(Image sourceBitmap, float darkness, int shadowSize, Point shadowOffset, Matrix matrix, PixelFormat targetPixelformat) { Point offset = shadowOffset; offset.X += shadowSize - 1; offset.Y += shadowSize - 1; - matrix.Translate(offset.X, offset.Y); + matrix.Translate(offset.X, offset.Y, MatrixOrder.Append); // Create a new "clean" image Bitmap returnImage = CreateEmpty(sourceBitmap.Width + (shadowSize * 2), sourceBitmap.Height + (shadowSize * 2), targetPixelformat, Color.Empty, sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution); // Make sure the shadow is odd, there is no reason for an even blur! @@ -865,7 +846,7 @@ namespace GreenshotPlugin.Core { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; // draw original with a TextureBrush so we have nice antialiasing! using (Brush textureBrush = new TextureBrush(sourceBitmap, WrapMode.Clamp)) { - // We need to do a translate-tranform otherwise the image is wrapped + // We need to do a translate-transform otherwise the image is wrapped graphics.TranslateTransform(offset.X, offset.Y); graphics.FillRectangle(textureBrush, 0, 0, sourceBitmap.Width, sourceBitmap.Height); } @@ -880,7 +861,7 @@ namespace GreenshotPlugin.Core { /// Negative bitmap public static Bitmap CreateNegative(Image sourceImage) { Bitmap clone = (Bitmap)Clone(sourceImage); - ColorMatrix invertMatrix = new ColorMatrix(new float[][] { + ColorMatrix invertMatrix = new ColorMatrix(new[] { new float[] {-1, 0, 0, 0, 0}, new float[] {0, -1, 0, 0, 0}, new float[] {0, 0, -1, 0, 0}, @@ -980,12 +961,12 @@ namespace GreenshotPlugin.Core { /// Size of the border /// Color of the border /// What pixel format must the returning bitmap have - /// How many pixels is the original image moved? + /// The transform matrix which describes how the elements need to be transformed to stay at the same location /// Bitmap with the shadow, is bigger than the sourceBitmap!! public static Image CreateBorder(Image sourceImage, int borderSize, Color borderColor, PixelFormat targetPixelformat, Matrix matrix) { // "return" the shifted offset, so the caller can e.g. move elements Point offset = new Point(borderSize, borderSize); - matrix.Translate(offset.X, offset.Y); + matrix.Translate(offset.X, offset.Y, MatrixOrder.Append); // Create a new "clean" image Bitmap newImage = CreateEmpty(sourceImage.Width + (borderSize * 2), sourceImage.Height + (borderSize * 2), targetPixelformat, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); @@ -1039,11 +1020,15 @@ namespace GreenshotPlugin.Core { attributes.SetGamma(gamma, ColorAdjustType.Bitmap); return attributes; } + /// /// Adjust the brightness, contract or gamma of an image. /// Use the value "1.0f" for no changes. /// /// Original bitmap + /// + /// + /// /// Bitmap with grayscale public static Image Adjust(Image sourceImage, float brightness, float contrast, float gamma) { //create a blank bitmap the same size as original @@ -1284,9 +1269,10 @@ namespace GreenshotPlugin.Core { /// /// /// + /// /// a new bitmap with the source copied on it public static Image ResizeCanvas(Image sourceImage, Color backgroundColor, int left, int right, int top, int bottom, Matrix matrix) { - matrix.Translate(left, top); + matrix.Translate(left, top, MatrixOrder.Append); Bitmap newBitmap = CreateEmpty(sourceImage.Width + left + right, sourceImage.Height + top + bottom, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using (Graphics graphics = Graphics.FromImage(newBitmap)) { graphics.DrawImageUnscaled(sourceImage, left, top); @@ -1301,6 +1287,7 @@ namespace GreenshotPlugin.Core { /// true to maintain the aspect ratio /// /// + /// /// public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) { return ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix); @@ -1310,7 +1297,7 @@ namespace GreenshotPlugin.Core { /// Count how many times the supplied color exists /// /// Image to count the pixels of - /// Color to count/param> + /// Color to count /// true if Alpha needs to be checked /// int with the number of pixels which have colorToCount public static int CountColor(Image sourceImage, Color colorToCount, bool includeAlpha) { @@ -1340,9 +1327,11 @@ namespace GreenshotPlugin.Core { /// /// Image to scale /// true to maintain the aspect ratio + /// /// The color to fill with, or Color.Empty to take the default depending on the pixel format /// new width /// new height + /// /// a new bitmap with the specified size, the source-Image scaled to fit with aspect ratio locked public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, bool canvasUseNewSize, Color backgroundColor, int newWidth, int newHeight, Matrix matrix) { int destX = 0; @@ -1351,8 +1340,8 @@ namespace GreenshotPlugin.Core { float nPercentW = 0; float nPercentH = 0; - nPercentW = ((float)newWidth / (float)sourceImage.Width); - nPercentH = ((float)newHeight / (float)sourceImage.Height); + nPercentW = (newWidth / (float)sourceImage.Width); + nPercentH = (newHeight / (float)sourceImage.Height); if (maintainAspectRatio) { if (nPercentW == 1) { nPercentW = nPercentH; @@ -1388,10 +1377,10 @@ namespace GreenshotPlugin.Core { Image newImage = null; if (maintainAspectRatio && canvasUseNewSize) { newImage = CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); - matrix.Scale(sourceImage.Width / newWidth, sourceImage.Height / newHeight); + matrix.Scale((float)newWidth / sourceImage.Width, (float)newHeight / sourceImage.Height); } else { newImage = CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); - matrix.Scale(sourceImage.Width / destWidth, sourceImage.Height / destHeight); + matrix.Scale((float)destWidth / sourceImage.Width, (float)destHeight / sourceImage.Height); } using (Graphics graphics = Graphics.FromImage(newImage)) {