WPF Canvas - 单像素网格

Lia*_*amV 6 wpf drawing canvas pixel

我有一个自定义的WPF Canvas,我想在其上显示一个网格.我这样做是通过覆盖Canvas上的OnRender方法,并使用DrawingContext绘图函数.IsGridVisible,GridWidth,GridHeight分别是水平和垂直每个网格线之间的像素数.

我还使用Canvas.LayoutTransform属性上的ScaleTransform来缩放Canvas项目,并且正如人们所期望的那样,网格线厚度乘以ScaleTransform缩放因子,如下图所示.有没有办法绘制单个像素线,无论当前的Canvas RenderTransform如何?

    protected override void OnRender(System.Windows.Media.DrawingContext dc)
    {
        base.OnRender(dc);

        if (IsGridVisible)
        {
            // Draw GridLines
            Pen pen = new Pen(new SolidColorBrush(GridColour), 1);
            pen.DashStyle = DashStyles.Dash;

            for (double x = 0; x < this.ActualWidth; x += this.GridWidth)
            {
                dc.DrawLine(pen, new Point(x, 0), new Point(x, this.ActualHeight));
            }

            for (double y = 0; y < this.ActualHeight; y += this.GridHeight)
            {
                dc.DrawLine(pen, new Point(0, y), new Point(this.ActualWidth, y));
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

alt text http://www.freeimagehosting.net/uploads/f05ad1f602.png

Lia*_*amV 1

正如对原帖状态的评论。笔粗细应设置为 1.0/缩放。