C# 为什么所有的坐标和大小都很奇怪?

C# 为什么所有的坐标和大小都很奇怪?,c#,wpf,rendertargetbitmap,C#,Wpf,Rendertargetbitmap,此代码生成了以下图像 DrawingVisual visual = new DrawingVisual(); DrawingContext ctx = visual.RenderOpen(); FormattedText txt = new FormattedText("45", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 100, Brushes.Red); ctx.DrawR

此代码生成了以下图像

DrawingVisual visual = new DrawingVisual();
DrawingContext ctx = visual.RenderOpen();

FormattedText txt = new FormattedText("45", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 100, Brushes.Red);
ctx.DrawRectangle(Brushes.White, new Pen(Brushes.White, 10), new System.Windows.Rect(0, 0, 400, 400));
ctx.DrawText(txt, new System.Windows.Point((300 - txt.Width)/2, 10));
ctx.Close();

RenderTargetBitmap bity = new RenderTargetBitmap(300, 300, 40, 40, PixelFormats.Default);
bity.Render(visual);
BitmapFrame frame = BitmapFrame.Create(bity);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(frame);
MemoryStream ms = new MemoryStream();
encoder.Save(ms);

如果位图是300x300,为什么白色矩形(0、0、400、400)只占一小部分为什么文本不居中


我甚至不知道谷歌用什么术语。我寻求智慧。

当您需要96时,您指定了40 DPI:

RenderTargetBitmap bity = new RenderTargetBitmap(300, 300, 96, 96, PixelFormats.Default);

注意:除了我最初的答案之外,在悬赏之后添加此项

对于初学者来说,不需要400x400背景矩形,因为您只渲染300x300位图,所以这里有第一个更改:

ctx.DrawRectangle(Brushes.White, new Pen(Brushes.White, 10), new System.Windows.Rect(0, 0, 300, 300));
有了这个变化,输出将完全相同,但它简化了解释

在可能和合乎逻辑的情况下,WPF使用DIP(设备独立像素)作为度量单位,而不是像素。执行此操作时:

<Rectangle Width="100" Height="100"/>
现在您可以将相关代码行更改为:

RenderTargetBitmap bity = new RenderTargetBitmap(300, 300, this.Dpi, this.Dpi, PixelFormats.Default);

无论您在哪个设备上运行,它都会工作。最终得到的位图总是300x300物理像素,并且源文件总是精确地填充它。

尝试使用实际宽度而不是Width@Tigran,这可能会解决问题,但这并不能解释为什么会发生这种情况。@lnuyasha:宽度是声明的大小,实际宽度是在您的计算机显示器上实际呈现的大小。我想,真的,我要寻找的答案是为什么我需要使用96而不是40。
RenderTargetBitmap bity = new RenderTargetBitmap(300, 300, this.Dpi, this.Dpi, PixelFormats.Default);