如何在Winforms按钮上的第二行文本中更改字体大小和颜色? [英] How to change font size and color in second line of text on a Winforms button?

查看:134
本文介绍了如何在Winforms按钮上的第二行文本中更改字体大小和颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 this.Controls.Add(button);
 button.Font = new Font("Arial", 8);
 button.Name = "btn" + idDanych;
 button.Width = 100;
 button.Height = 100;
 button.Location = new Point(0, 0);
 button.Text = "…" + Environment.NewLine + Environment.NewLine + "…";
 button.ForeColor = Color.Black;

如何更改按钮第二行文本的字体大小和颜色?

How can I change the font size and color in the button's second line of text?

推荐答案

无法使用.Text属性...

...但是您可以创建一个动态位图来代替文本,从而可以根据需要设置其格式:

...but you can create a dynamic Bitmap to take the place of the Text, allowing you to format it however you want:

        Button button = new Button();
        button.Name = "btn" + idDanych;
        button.Width = 100;
        button.Height = 100;
        button.Location = new Point(0, 0);

        button.Text = "";
        Bitmap bmp = new Bitmap(button.ClientRectangle.Width, button.ClientRectangle.Height);
        using (Graphics G = Graphics.FromImage(bmp))
        {
            G.Clear(button.BackColor);

            string line1 = "( " + Wieszak + " ) " + Haczyk;
            string line2 = KodEAN;

            StringFormat SF = new StringFormat();
            SF.Alignment = StringAlignment.Center;
            SF.LineAlignment = StringAlignment.Near;
            using (Font arial = new Font("Arial", 12))
            {
                Rectangle RC = button.ClientRectangle;
                RC.Inflate(-5, -5);
                G.DrawString(line1, arial, Brushes.Black, RC, SF);
            }

            using (Font courier = new Font("MS Courier", 24))
            {
                SF.LineAlignment = StringAlignment.Center;
                G.DrawString(line2, courier, Brushes.Red, button1.ClientRectangle, SF);
            }
        }
        button.Image = bmp;
        button.ImageAlign = ContentAlignment.MiddleCenter;

        this.Controls.Add(button);

您将必须找出字体大小,StringFormat布局和/或位置的最佳组合,以使其看起来理想.还有其他DrawString()重载以不同的方式呈现文本.

You'll have to figure out the best combination of font sizes, StringFormat layouts, and/or positioning to make it look as desired. There are other DrawString() overloads to render the text in different ways.

但是请注意,控件的突出显示方式将有所不同.在我的系统上,当鼠标进入时,标准按钮的整个区域都会突出显示.使用此方法,由于按钮的整个中间都是静态图像,因此仅边框会突出显示.

Note that there will be a difference in how the control highlights, however. On my system, the entire area of the standard button highlights when the mouse enters. With this approach only the border will highlight since the entire middle of the button is a static image.

这篇关于如何在Winforms按钮上的第二行文本中更改字体大小和颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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