带有图形变换的文本渲染器
我一直在开发自定义控件,但遇到了 TextRenderer 表现有点令人惊讶的问题。在我的 OnPaint 事件中,我将变换应用于 Graphics 对象以补偿滚动位置,如下所示:
e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
然后,我将图形对象传递给控件的所有子元素,以便它们将自己绘制到其上。该元素之一应将文本字符串绘制到图形表面上。这就是我遇到的问题。这条线在滚动时似乎可以正常工作:
e.Graphics.DrawString(this.Text, this.Font, brush, new PointF(this.Rectangle.X, this.Rectangle.Y));
但是当我使用 TextRenderer 时,我得到了完全不同的结果。这是应该绘制文本的文本行:
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.Rectangle, this.TextColor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform);
我认为这两行应该产生相同的结果。但由于某种原因,第二个以不同的方式应用图形变换,因此,当我滚动控件时,所有文本行以与绘图表面上的其他元素不同的速度移动。有人可以解释一下为什么会发生这种情况吗?
I've been working on a custom control and I've run into an issue with TextRenderer acting a bit surprisingly. In my OnPaint event I apply transform to the Graphics object to compensate for the scroll position like this:
e.Graphics.Transform = new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
Then I pass the graphic object to all sub elements of the control so that they paint themselves onto it. One of this elements should draw text string onto the graphics surface. And this is where I've got an issue. This line seems to work correctly when scrolling:
e.Graphics.DrawString(this.Text, this.Font, brush, new PointF(this.Rectangle.X, this.Rectangle.Y));
But when I use TextRenderer I get a completely different result. Heres the text line that supposed to draw the text:
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.Rectangle, this.TextColor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform);
I thought that these two lines should produce the same result. But for some reason the second one applies the graphics transform differently and as a result, when I scroll the control all the text lines move around with different speed than the rest of the elements on the drawing surface. Could someone explain me why this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我对此的最佳猜测: TextRenderer.DrawText 是基于 GDI 的并且因此取决于分辨率。 Graphics.DrawString 是 GDI+,因此分辨率-独立的。另请参阅本文。
既然您说文本“以不同的速度移动”,那么可能会发生的情况是 GDI 调用使用与 Graphics 对象不同的“默认”分辨率。这意味着您必须调整 AutoScrollCoordinates 以尊重 Graphics 对象分辨率和“默认”GDI 分辨率之间的差异。
Here's my best guess at this: TextRenderer.DrawText is GDI-based and therefore resolution-dependant. Graphics.DrawString is GDI+ and therefore resolution-independant. See also this article.
Since you say that the texts "move around with different speed", probably what happens is that the GDI call uses a different "default" resolution than the one your Graphics object has. That'd mean that you'd have to adjust your AutoScrollCoordinates to respect the difference between your Graphics object resolution and the "default" GDI resolution.