使用鼠标绘图会在像素之间留下间隙

5
我一直在为WPF创建一个绘图应用程序,进展顺利。我遇到的问题是,如果每次鼠标移动时将像素绘制到位图中,我每次只能得到一个像素。当鼠标快速移动时,它不会绘制中间的像素。我需要知道在WPF中使用WriteableBitmap以最佳方式绘制两个像素之间的线条。
编辑:现在我有这个: LinesNotConnected

可能是重复问题:https://dev59.com/O07Sa4cB1Zd3GeqP2U-o - Mr Lister
2个回答

3
如果您想画一条线,不应该只是一次更改一个像素的颜色,而是应该在每个MouseMove事件处理方法中保存鼠标的位置。然后,您应该在上一个位置(从上一个事件发生时保存的位置)和两个点之间画出一条直线。这将使线变得连续。有关在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>

然后,在代码后面添加事件处理程序:
//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);
        }
    }

Bitmap类在哪个命名空间中?我必须使用gdi+中的类吗? - annonymously
好的,现在它的工作效果更好了,但是线条没有连接。请查看我的更新问题。 - annonymously

2
我知道你已经得到了答案,但我想为那些遇到同样问题的人提供帮助。我就是其中之一。
我的情况是,我的图纸看起来与原问题中的UPDATE部分完全相同。我通过绘制重叠线条来解决这个问题,不仅跟踪起点和终点,还跟踪中点。当我绘制时,我使用三个点进行绘制,然后更新起点 -> 中点,中点 -> 终点,终点 -> 相对于你正在绘制的任何东西的新位置。这使我的线条看起来好多了。
希望这对于有同样问题的人有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接