Smoothing problem

The code below draws two vertical lines on the canvas. these lines appear to be of different thicknesses on the screen, although they are the same in the code. I get attached to find a way to make them as sharp as the border around the canvas. setting Path.SnapsToDevicePixels has no effect. The code is a contrived example, and in general the canvas that displays these lines can be nested deeper inside the visual tree.

thanks for any help


<Window x:Class="wpfapp.MyWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>
    <Border BorderBrush="Black"
            BorderThickness="1"
            Margin="10">
      <Canvas x:Name="Canvas"
              SizeChanged="OnCanvasSizeChanged" />
    </Border>
  </Grid>
</Window>

using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace wpfapp
{
    public partial class MyWindow : Window
    {
        public MyWindow()
        {
            InitializeComponent();
        }

        private void OnCanvasSizeChanged(object sender, SizeChangedEventArgs e)
        {
            StreamGeometry g = new StreamGeometry();
            double h = this.Canvas.ActualHeight;

            using (StreamGeometryContext c = g.Open())
            {
                c.BeginFigure(new Point(7, 0), false, false);
                c.LineTo(new Point(7, h), true, false);

                c.BeginFigure(new Point(14, 0), false, false);
                c.LineTo(new Point(14, h), true, false);
            }
            g.Freeze();

            Path p = new Path();

            p.Data = g;
            p.SnapsToDevicePixels = true;
            p.Stroke = new SolidColorBrush(Colors.Black);
            p.StrokeThickness = 1;

            this.Canvas.Children.Clear();
            this.Canvas.Children.Add(p);
        }
    }
}
+3
source share
1 answer

must use GuidelineSet:


        protected override void OnRender(DrawingContext c)
        {
            base.OnRender(c);

            Pen pen = new Pen(Brushes.Black, 1);
            double h = this.ActualHeight;
            double d = pen.Thickness / 2;

            foreach (double x in new double[] { 7, 14 })
            {
                GuidelineSet g = new GuidelineSet(new double[] { x + d },
                                                  new double[] { 0 + d, h + d });

                c.PushGuidelineSet(g);
                c.DrawLine(pen, new Point(x, 0), new Point(x, h));
                c.Pop();
            }
        }
+2
source

Source: https://habr.com/ru/post/1771740/


All Articles