我需要在WinForms按钮中添加两行作为文本,因此我找到了this解决方案。我需要第一行,上面的,用黑色打印,第二行,在第一行,用红色打印。我的问题是背景矩形不透明。我需要背景矩形透明,所以我做了一些改进但没有成功。另外第一行打印在顶部而不是中心(垂直),两行之间的距离(行间距)有太多的分离。我想减少它,并在按钮内的两条线垂直居中。代码下方。
private void TextButton(Button btn, string line1, string line2)
{
btn.Text = String.Empty;
Bitmap bmp = new Bitmap(btn.ClientRectangle.Width, btn.ClientRectangle.Height);
using (Graphics G = Graphics.FromImage(bmp))
{
G.Clear(btn.BackColor);
StringFormat SF = new StringFormat();
SF.Alignment = StringAlignment.Center;
SF.LineAlignment = StringAlignment.Near;
using (Font tahoma = new Font("Tahoma", 15.75F, System.Drawing.FontStyle.Bold))
{
Rectangle RC = btn.ClientRectangle;
RC.Inflate(-5, -5);
G.FillRectangle(Brushes.Transparent,RC.X,RC.Y,RC.Width,RC.Height);
G.DrawString(line1, tahoma, Brushes.Black, RC, SF);
}
using (Font tahoma2 = new Font("Tahoma", 12))
{
SF.LineAlignment = StringAlignment.Center;
G.FillRectangle(Brushes.Transparent,btn.ClientRectangle.X,btn.ClientRectangle.Y,btn.ClientRectangle.Width,btn.ClientRectangle.Height);
G.DrawString(line2, tahoma2, Brushes.Red, btn.ClientRectangle, SF);
}
}
btn.Image = bmp;
btn.ImageAlign = ContentAlignment.MiddleCenter;
}
答案 0 :(得分:0)
最后我已经解决了。在我的解决方案之下。
private void TextButton(Button btn, string line1, string line2)
{
btn.Text = String.Empty;
Bitmap bmp = new Bitmap(btn.ClientRectangle.Width, btn.ClientRectangle.Height);
using (Graphics G = Graphics.FromImage(bmp))
{
G.Clear(Color.Transparent); <----- I have set this
G.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; <--- This to avoid bad text within bitmap
G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; <--- Also this to avoid bad text within bitmap
StringFormat SF = new StringFormat();
SF.Alignment = StringAlignment.Center;
SF.LineAlignment = StringAlignment.Near;
using (Font tahoma = new Font("Tahoma", 15.75F, System.Drawing.FontStyle.Bold))
{
Rectangle RC = new Rectangle(btn.ClientRectangle.X, btn.ClientRectangle.Y + 30, btn.ClientRectangle.Width, btn.ClientRectangle.Height-30);
RC.Inflate(-5, -5);
G.DrawString(line1, tahoma, Brushes.Black, RC, SF);
}
using (Font tahoma2 = new Font("Tahoma", 12))
{
Rectangle RC = new Rectangle(btn.ClientRectangle.X, btn.ClientRectangle.Y + 30, btn.ClientRectangle.Width, btn.ClientRectangle.Height-30);
RC.Inflate(-5, -5);
SF.LineAlignment = StringAlignment.Center;
G.DrawString(line2, tahoma2, Brushes.Red, RC, SF);
}
}
btn.Image = bmp;
btn.ImageAlign = ContentAlignment.MiddleCenter;
}