按标签大小缩放标签文本 [英] Scale Label text in line with Label size

查看:220
本文介绍了按标签大小缩放标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种方法来根据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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆