0

我使用下面的代码为 Windows 窗体中的按钮设置渐变。它有效,但它的文本没有显示。我应该怎么做才能修复它?谢谢你。

 private void Form1_Load(object sender, EventArgs e)
 {
       button2.Paint += new PaintEventHandler(this.Button2_Paint);
 }
 private void Button2_Paint(object sender, PaintEventArgs e)
 {
      Graphics g = e.Graphics;
      g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(PointF.Empty, new PointF(button2.Width, button2.Height), Color.Pink, Color.Red), new RectangleF(PointF.Empty, button2.Size));
  }
4

1 回答 1

0

It's because you never actually drawing that text. Currently you only filling button's client rectangle with gradient, but there is no any text within. To show the string with button's text you need to add some more lines to Paint method:

 private void Button2_Paint(object sender, PaintEventArgs e)
 {
    Button btn= (Button)sender;
    Graphics g = e.Graphics;
    g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(PointF.Empty, new PointF(button2.Width, button2.Height), Color.Pink, Color.Red), new RectangleF(PointF.Empty, button2.Size));
    SizeF size = g.MeasureString(btn.Text, btn.Font);
    PointF topLeft = new PointF(btn.Width / 2 - size.Width / 2, btn.Height / 2 - size.Height / 2);
    g.DrawString(btn.Text, btn.Font, Brushes.Black, topLeft);
  }

Here Graphics.MeasureString gives you the width and height of a button's Text property, these values are used to position text right in the middle of a button. And Graphics.DrawString just draws the string with supplied color, font and position.

于 2013-10-05T22:45:30.180 回答