用鼠标绘图会导致像素之间的间隙

ann*_*sly 5 c# wpf graphics drawing bitmap

我一直在创建一个绘图应用程序作为WPF的测试,并且一直进展顺利.我遇到的问题是,如果我每次移动时将鼠标下的像素绘制到位图,我每次更新只会获得一个像素.当鼠标快速移动时,它不会在其间绘制像素.我需要知道在WPF中使用的最佳方法是在像素之间画一条线WriteableBitmap

编辑:现在我有这个:

LinesNotConnected

Luk*_*z M 3

如果你想画一条线,你不应该一次只改变一个像素的颜色,而应该在每个MouseMove事件处理方法中保存鼠标的位置。

然后,您应该在前一个位置(从上一次事件发生时保存的位置)之间画一条线Line,并在这两点之间画一条线。这将使线条连续。有关绘制线条的信息WriteableBitmap可以在此处找到:使用 WPF WriteableBitmap.BackBuffer 绘制线条

绘制线条后,不要忘记将之前保存的位置更新为当前位置:)。

更新

我还找到了另一个解决方案。

使用要在其上绘制的图像定义 XAML:

<Window x:Class="SampleWPFApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="500" Width="520" Loaded="Window_Loaded" PreviewMouseDown="Window_PreviewMouseDown">
<Grid x:Name="layoutRoot" Background="Transparent">
    <Image x:Name="image" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

然后,在处理的事件后面添加代码:

//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;
    }

    /// <summary>
    /// Helper method drawing a line.
    /// </summary>
    /// <param name="p1">Start point of the line to draw.</param>
    /// <param name="p2">End point of the line to draw.</param>
    /// <param name="pen">Pen to use to draw the line.</param>
    /// <param name="thickness">Thickness of the line to draw.</param>
    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)