Winform的Button控件的外观着实让人产生不了美感,虽然Button控件有BackColor,FlatStyle等属性但是仍然不能满足日常软件开发的需要。现在软件设计的美感要求越来越高。现在软件UI设计中有很多圆角的设计,在winform中实现圆角必须要自己绘制还是比较麻烦的,笔者实现了圆角矩形的自绘。
代码如下。
private void btnStopAnswer_Paint(object sender, PaintEventArgs e)
{
//放到button的Paint事件实现起来会更好
//结束作答按钮
this.btnStopAnswer.Text = string.Empty;
int rectWidth = 36, rectHeight = 36, sumWidth = 126, radius = 18;
GraphicsPath gp = new GraphicsPath();
Pen p = new Pen(new SolidBrush(bottomBackColor), 1);
Rectangle leftRectangle = new Rectangle(0, 0, rectWidth, rectHeight);
Rectangle rightRectangle = new Rectangle(sumWidth - rectWidth, 0, rectWidth, rectHeight);
//Graphics gbtn = this.btnStopAnswer.CreateGraphics(); 使用这种方式会出现显示不正常的现象。
Graphics gbtn = e.Graphics;
//gbtn.DrawArc(p, leftRectangle, 90, 180);
//gbtn.DrawLine(p, new Point(radius, 0), new Point(sumWidth - radius, 0));
//gbtn.DrawArc(p, rightRectangle, 270, 180);
//gbtn.DrawLine(p, new Point(radius, rectHeight), new Point(sumWidth - radius, rectHeight));
gp.AddArc(leftRectangle, 90, 180);
gp.AddLine(new Point(radius, 0), new Point(sumWidth - radius, 0));
gp.AddArc(rightRectangle, 270, 180);
gp.AddLine(new Point(radius, rectHeight), new Point(sumWidth - radius, rectHeight));
//gp.AddString("结束作答",this.btnStopAnswer.Font.FontFamily,(int)FontStyle.Regular,18, new PointF((this.btnStopAnswer.Width * 1.0f - this.btnStopAnswer.Font.Size * 4) / 2, (this.btnStopAnswer.Height * 1.0f - 25) / 2),new StringFormat(StringFormatFlags.NoWrap));
gbtn.FillPath(new SolidBrush(ColorTranslator.FromHtml("#f89009")), gp);
gbtn.DrawString("结束作答", new Font("微软雅黑", 18, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF((this.btnStopAnswer.Width * 1.0f - this.btnStopAnswer.Font.Size * 4) / 2, (this.btnStopAnswer.Height * 1.0f - 25) / 2));
this.btnStopAnswer.Region = new Region(gp); //没有这句话FlatAppearance属性无法被屏蔽
}
效果如图。