按标签大小缩放标签文本 [英] Scale Label text in line with Label size
问题描述
寻找一种方法来根据Label
的大小变化来调整Labels
文本的大小. (即,如果标签的大小增加50%
,则文本的大小也应增加大约50%
).
Looking for a way to resize a Labels
text in line with the change in size of the Label
. (ie. should a label increase in size by 50%
, then the text should also increase in size by approx 50%
).
有很多文章围绕它们调整文本以完全适合Label
的大小,这不适合我想要的内容.
我已经有这个版本了.
There is plenty of articles around which adjust the text to fit fully within the size of a Label
, which isn't suitable for what I want.
I already have a working version of this.
以某种方式,一旦调整大小,我需要能够引用Label
的先前大小,以便确定用于调整文本大小的比例.
Somehow I need to be able to reference the previous size of a Label
once the resize is complete in order to determine the ratio to use in order to resize the text.
推荐答案
An example using Graphics.ScaleTransform(), used to prepend a transformation matrix to the Graphics operations that follow.
请注意,只要图形可以绘制给定大小的字体,此转换就适用.如果Font太小或太大,则渲染将无法正常工作.
最小字体大小应为8.5 ~ 9
点,并且不得超过72
.
在此范围之外,结果是不可预测的. (例如,文本可能会消失).
因此,控件的最小/最大尺寸应在设计时设置,并且不要超出这些度量范围.
Note that this transformation is applicable as long as the Graphics can draw a Font in a given size. If the Font is too small or too large, the rendering will not work as expected.
The minimum Font size should be 8.5 ~ 9
points and no more than 72
.
Outside this range, the result are unpredictable. (e.g., the Text may simply disappear).
Thus, a Control minimum/maximum size should be set at design time and not be scaled beyond these measures.
此处的Label.TextAlign
属性设置为ContentAlignment.MiddleLeft
.
另外:.AutoSize = false;
.Text = "Some text that needs to fit";
The Label.TextAlign
property is set to ContentAlignment.MiddleLeft
here.
Also: .AutoSize = false;
.Text = "Some text that needs to fit";
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
private void label1_Paint(object sender, PaintEventArgs e)
{
Label label = sender as Label;
e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
float TextWidth = e.Graphics.MeasureString(label.Text, label.Font, label.Size, StringFormat.GenericTypographic).Width;
float scale = (label.ClientSize.Width - label.Padding.Left) / TextWidth;
e.Graphics.Clear(label.BackColor);
e.Graphics.ScaleTransform(scale, scale);
using (SolidBrush brush = new SolidBrush(label.ForeColor))
e.Graphics.DrawString(label.Text, label.Font, brush,
new RectangleF(PointF.Empty, label1.ClientSize),
StringFormat.GenericTypographic);
}
视觉效果:
这篇关于按标签大小缩放标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!