下面的代码在画布上绘制两条垂直线。这些线在屏幕上看起来有不同的厚度,尽管它们在代码中是相同的。我想找到一种方法让它们看起来像画布周围的边框一样锋利。设置Path.SnapsToDevicePixels没有任何效果。代码是一个人为的例子,一般来说,绘制这些线条的画布可以嵌套在可视树中更深处。
感谢您的帮助 康斯坦丁
<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);
}
}
}
答案 0 :(得分:2)
需要使用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();
}
}