I have been creating a drawing app as a test for WPF, and have been going well. The problem I\'ve run into is that if I draw the pixel under the mouse to a bitmap each time
If you want to draw a line, you shouldn't just change colors of one pixel at a time, but rather save position of the mouse in each MouseMove event handling method.
Then, you should draw a line between previous position (the one saved from the previous event occurrence) and draw a Line between those two points. This will make the line to be continuous. Information about drawing lines on WriteableBitmap can be found here: Drawing line using WPF WriteableBitmap.BackBuffer.
After drawing the line, don't forget to update the previous position saved to the current one :).
UPDATE
I've also found another solution.
Define XAML with Image you want to draw on:
And then, add code behind with the events handled:
//set width and height of your choice
RenderTargetBitmap bmp = null;
//...
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//initialize RenderTargetBitmap object
bmp = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 90, 90, PixelFormats.Default);
//set initialized bmp as image's source
image.Source = bmp;
}
///
/// Helper method drawing a line.
///
/// Start point of the line to draw.
/// End point of the line to draw.
/// Pen to use to draw the line.
/// Thickness of the line to draw.
private void DrawLine(Point p1, Point p2, Pen pen, double thickness)
{
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
//set properties of the Pen object to make the line more smooth
pen.Thickness = thickness;
pen.StartLineCap = PenLineCap.Round;
pen.EndLineCap = PenLineCap.Round;
//write your drawing code here
drawingContext.DrawLine(pen, p1, p2);
}
}