我正试图找出一种很好的方法来自动调整Rectangle的大小,并在其中绘制文本。我基本上希望尺寸有一个宽度/高度的比率,然后根据这个比例“增长”,以适应文本。我看过Graphics.MeasureString,但我不认为它能做我想要的(也许它做了,我只是用错了)。
我不想指定要绘制的矩形的特定宽度。相反,我想说,找到最小的宽度/高度,以适应这篇文章,给出一个最小的宽度,但发现的矩形必须有一定的宽度和高度的特定比率。
这不一定是特定于C#的,解决这个问题的任何想法都可以映射到C#。
谢谢!
发布于 2010-05-20 17:30:39
我找到了自己的解决方案。下面的代码确定适合文本的最佳矩形(匹配比率)。它使用“分而治之”来找到最接近的矩形(通过将宽度减少一些“步骤”)。这个算法使用的是一个始终满足的最小宽度,我确信这可以修改为包含一个最大宽度。有什么想法?
private Size GetPreferredSize(String text, Font font, StringFormat format)
{
Graphics graphics = this.CreateGraphics();
if (format == null)
{
format = new StringFormat();
}
SizeF textSize = SizeF.Empty;
// The minimum width allowed for the rectangle.
double minWidth = 100;
// The ratio for the height compared to the width.
double heightRatio = 0.61803399; // Gloden ratio to make it look pretty :)
// The amount to in/decrement for width.
double step = 100;
// The new width to be set.
double newWidth = minWidth;
// Find the largest width that the text fits into.
while (true)
{
textSize = graphics.MeasureString(text, font, (int)Math.Round(newWidth), format);
if (textSize.Height <= newWidth * heightRatio)
{
break;
}
newWidth += step;
}
step /= 2;
// Continuously divide the step to adjust the rectangle.
while (true)
{
// Ensure step.
if (step < 1)
{
break;
}
// Ensure minimum width.
if (newWidth - step < minWidth)
{
break;
}
// Try to subract the step from the width.
while (true)
{
// Measure the text.
textSize = graphics.MeasureString(text, font, (int)Math.Round(newWidth - step), format);
// If the text height is going to be less than the new height, decrease the new width.
// Otherwise, break to the next lowest step.
if (textSize.Height < (newWidth - step) * heightRatio)
{
newWidth -= step;
}
else
{
break;
}
}
step /= 2;
}
double width = newWidth;
double height = width * heightRatio;
return new Size((int)Math.Ceiling(width), (int)Math.Ceiling(height));
}发布于 2010-05-20 15:33:24
我相信你可以使用Graphics.MeasureString。这就是我在GUI代码中所使用的,用来绘制文本周围的矩形。您将文本和想要使用的字体交给它,它将返回一个矩形(从技术上讲,它是一个SizeF对象-宽度和高度)。然后,您可以根据所需的比率调整此矩形:
Graphics g = CreateGraphics();
String s = "Hello, World!";
SizeF sizeF = g.MeasureString(s, new Font("Arial", 8));
// Now I have a rectangle to adjust.
float myRatio = 2F;
SizeF adjustedSizeF = new SizeF(sizeF.Width * myRatio, sizeF.Height * myRatio);
RectangleF rectangle = new RectangleF(new PointF(0, 0), adjustedSizeF);我正确地理解了你的问题吗?
发布于 2010-05-20 16:21:21
您应该使用TextRenderer.MeasureText,所有控件都使用TextRenderer在.NET 2.0及更高版本中绘制文本。
没有明确的解决方案,您的问题,有许多可能的方式,以适应一个矩形文本。只显示一行的宽行与显示多行的窄行一样有效。你必须限制其中一个维度。这是一个现实的要求,这个矩形显示在其他控件中,并且该控件具有一定的ClientSize。你得决定你要怎么说。
https://stackoverflow.com/questions/2875216
复制相似问题