【发布时间】:2017-05-29 03:12:50
【问题描述】:
我试图在用户创建的多边形的中心放置一个标签(字符串)。我检查了 Graphics 类的可用方法,但只找到了 DrawString 方法,它采用字符串、字体和矩形。问题是我使用的是多边形。并且没有将字符串作为参数的 DrawPolygon 重载。
// Get the highest and lowest of both axis to
// determine the width and height of the polygon
int _lowestX = _slot.Min(o => o.X);
int _highestX = _slot.Max(o => o.X);
int _lowestY = _slot.Min(o => o.Y);
int _highestY = _slot.Max(o => o.Y);
// Draw the polygon
e.Graphics.FillPolygon(Brushes.White, _slot.ToArray()); // _slot is a list of points
e.Graphics.DrawPolygon(Pens.Blue, _slot.ToArray());
Font _font = new Font(FontFamily.GenericSansSerif, _highestX - _lowestX, FontStyle.Regular);
SizeF _textSize = e.Graphics.MeasureString("Slot 1", _font);
// My attempt at drawing the text using the DrawString method
// by trying to mock a rectangle using the height and width of the polygon
e.Graphics.DrawString("Slot 1", _font, new SolidBrush(Color.Black), (_highestX - _lowestX - _textSize.Width) / 2, 0);
有什么建议吗?
提前致谢。
【问题讨论】:
-
你想在哪里绘制你的字符串?多边形内部还是外部?...居中还是沿边缘?给我们一些关于如何计算点和/或绘制多边形的代码,然后解释或模拟你希望如何绘制字符串。移动和旋转图形表面是相当容易的,这样你的字符串就会与多边形对齐;我们只需要更多细节。
-
嗨,我编辑了我的原始帖子以展示我到目前为止所做的事情。我希望将字符串绘制在多边形的中心,在里面。
-
简单:放置文本,使其质心位于多边形边界框的中心。直截了当:将文本的质心放在多边形的质心。真的很难:将文本放置到所有边缘的距离一致且最大化。
-
我要试试 Easy 版本。如何找到字符串的质心?
标签: c# winforms graphics polygon