c#如何添加圆角按钮
本文关键字:圆角 按钮 添加 何添加 | 更新日期: 2023-09-27 17:50:29
我需要帮助如何在每个角上添加曲线。
这是我的代码…
using (Graphics btnG = pevent.Graphics)
using (SolidBrush btnBGSB = new SolidBrush(Color.FromArgb(107, 109, 110)))
using (SolidBrush lblBrush = new SolidBrush(Color.FromArgb(255, 255, 255)))
{
Rectangle btnBG = new Rectangle(0, 0, this.Width, this.Height);
btnG.FillRectangle(btnBGSB, btnBG);
RectangleF lblRec = new RectangleF(0, 0, this.Width - 1, this.Height - 1);
StringFormat lblSf = new StringFormat();
lblSf.Alignment = StringAlignment.Center;
lblSf.LineAlignment = StringAlignment.Center;
btnG.DrawString(this.Text, new Font("tahoma", 10.0f, FontStyle.Bold), lblBrush, lblRec, lblSf);
}
这是我玩c#的第三天…只是一个GUI为我的TCPSocket应用程序…:)
这是我用来制作圆角的方法:
public static void DrawRoundedRectangle(this Graphics g, Color color, Rectangle rec, int radius,
RoundedCorners corners)
{
using (var b = new SolidBrush(color))
{
int x = rec.X;
int y = rec.Y;
int diameter = radius * 2;
var horiz = new Rectangle(x, y + radius, rec.Width, rec.Height - diameter);
var vert = new Rectangle(x + radius, y, rec.Width - diameter, rec.Height);
g.FillRectangle(b, horiz);
g.FillRectangle(b, vert);
if ((corners & RoundedCorners.TopLeft) == RoundedCorners.TopLeft)
g.FillEllipse(b, x, y, diameter, diameter);
else
g.FillRectangle(b, x, y, diameter, diameter);
if ((corners & RoundedCorners.TopRight) == RoundedCorners.TopRight)
g.FillEllipse(b, x + rec.Width - (diameter + 1), y, diameter, diameter);
else
g.FillRectangle(b, x + rec.Width - (diameter + 1), y, diameter, diameter);
if ((corners & RoundedCorners.BottomLeft) == RoundedCorners.BottomLeft)
g.FillEllipse(b, x, y + rec.Height - (diameter + 1), diameter, diameter);
else
g.FillRectangle(b, x, y + rec.Height - (diameter + 1), diameter, diameter);
if ((corners & RoundedCorners.BottomRight) == RoundedCorners.BottomRight)
g.FillEllipse(b, x + rec.Width - (diameter + 1), y + rec.Height - (diameter + 1), diameter, diameter);
else
g.FillRectangle(b, x + rec.Width - (diameter + 1), y + rec.Height - (diameter + 1), diameter,
diameter);
}
}
public enum RoundedCorners
{
None = 0x00,
TopLeft = 0x02,
TopRight = 0x04,
BottomLeft = 0x08,
BottomRight = 0x10,
All = 0x1F
}
这样你就可以指定你想要圆角的角。
如果你想在它周围加一个边框,使用这个方法:
public static void DrawRoundedBorder(this Graphics g, Color color, Rectangle rec,
int radius, int borderWidth, RoundedCorners corners)
{
using (Bitmap b = new Bitmap(rec.Width, rec.Height))
using (Graphics gb = Graphics.FromImage(b))
{
var gfRec = new Rectangle(0, 0, rec.Width, rec.Height);
gb.Clear(Color.Green);
gb.DrawRoundedRectangle(color, gfRec, radius, corners);
gfRec.Height -= borderWidth << 1;
gfRec.Width -= borderWidth << 1;
gfRec.X += borderWidth;
gfRec.Y += borderWidth;
gb.DrawRoundedRectangle(Color.Green, gfRec, radius - borderWidth, corners);
var maskAttr = new ImageAttributes();
maskAttr.SetColorKey(Color.Green, Color.Green);
g.DrawImage(b, rec, 0, 0, b.Width, b.Height, GraphicsUnit.Pixel, maskAttr);
}
}