c# - WinForms:在正确的位置绘制路径
问题描述
这是我在这里提出的一个问题的后续:WinForms: Measure Text With No Padding。问题是,鉴于此代码...
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
DrawIt(e.Graphics);
}
private void DrawIt(Graphics graphics) {
var text = "123";
var font = new Font("Arial", 72);
// Build a path containing the text in the desired font, and get its bounds.
GraphicsPath path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), StringFormat.GenericDefault);
var bounds = path.GetBounds();
// Find center of the form.
var cx = this.ClientRectangle.Left + this.ClientRectangle.Width / 2;
var cy = this.ClientRectangle.Top + this.ClientRectangle.Height / 2;
// Move it where I want it.
var xlate = new Matrix();
xlate.Translate(cx - bounds.Width / 2, cy - bounds.Height / 2);
path.Transform(xlate);
// Draw the path (and a bounding rectangle).
graphics.DrawPath(Pens.Black, path);
bounds = path.GetBounds();
graphics.DrawRectangle(Pens.Blue, bounds.Left, bounds.Top, bounds.Width, bounds.Height);
// This rectangle doesn't use the positioning from Translate but does use the same size.
graphics.DrawRectangle(Pens.Red, cx - bounds.Width / 2, cy - bounds.Height / 2, bounds.Width, bounds.Height);
}
...为什么矩形不重叠?
显然,当我翻译路径时,我并没有使用稍后绘制它们的相同单位进行翻译,但我不知道如何修复它。有任何想法吗?
解决方案
Bounds
您对路径有错误的假设。由于您将字符串添加到路径,从 point 开始(0,0)
,您假设路径边界的位置是(0,0)
。这是不正确的。
下图显示了您添加字符串的原点(0,0)
与路径边界(蓝色矩形)之间的关系:
要修复它,在添加字符串并获取其边界后,存储边界的位置:
var p = bounds.Location;
然后在应用转换后,以这种方式绘制矩形:
graphics.DrawRectangle(Pens.Red,
p.X + cx - bounds.Width / 2, p.Y + cy - bounds.Height / 2,
bounds.Width, bounds.Height);
推荐阅读
- java - 需要解释这个 UML 模型
- c++ - 如何使用我创建的 map 函数来打印数组的值
- php - 使用 php、ffmpeg 和 proc_open 逐帧读取视频
- python - 有没有办法扫描目录以查看有多少特定类型的文件?
- docker - Docker 构建未检测到 React 生产构建文件中的更改
- facebook - 无法使用 Graph API 查询 Instagram 用户
- php - 如何在数组中找到下一个较大的数字和下一个较小的数字
- javascript - 有人可以告诉我为什么我的变量在函数之外而不是在函数内部工作
- reactjs - React-router 将错误的组件与类似的匹配匹配
- python - 在具有 dna 序列的字典中查找重复次数最多的子字符串