using System.Drawing.Drawing2D;namespace iptools;public class RoundButton : Button{public int CornerRadius { get; set; } = 12;public Color HoverBackColor { get; set; } = Color.Empty;public Color PressedBackColor { get; set; } = Color.Empty;private bool _isHovered;private bool _isPressed;public RoundButton(){FlatStyle = FlatStyle.Flat;FlatAppearance.BorderSize = 0;Cursor = Cursors.Hand;Resize += (_, _) => UpdateRegion();}protected override void OnMouseEnter(EventArgs e){_isHovered = true;Invalidate();base.OnMouseEnter(e);}protected override void OnMouseLeave(EventArgs e){_isHovered = false;_isPressed = false;Invalidate();base.OnMouseLeave(e);}protected override void OnMouseDown(MouseEventArgs mevent){_isPressed = true;Invalidate();base.OnMouseDown(mevent);}protected override void OnMouseUp(MouseEventArgs mevent){_isPressed = false;Invalidate();base.OnMouseUp(mevent);}protected override void OnPaint(PaintEventArgs pevent){pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;pevent.Graphics.Clear(Parent?.BackColor ?? SystemColors.Control);var rect = ClientRectangle;rect.Width -= 1;rect.Height -= 1;using var path = CreateRoundPath(rect, CornerRadius);using var brush = new SolidBrush(GetCurrentBackColor());pevent.Graphics.FillPath(brush, path);TextRenderer.DrawText(pevent.Graphics,Text,Font,rect,ForeColor,TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);}private Color GetCurrentBackColor(){if (_isPressed && PressedBackColor != Color.Empty){return PressedBackColor;}if (_isHovered && HoverBackColor != Color.Empty){return HoverBackColor;}return BackColor;}private void UpdateRegion(){if (Width <= 0 || Height <= 0){return;}using var path = CreateRoundPath(new Rectangle(0, 0, Width, Height), CornerRadius);Region = new Region(path);}private static GraphicsPath CreateRoundPath(Rectangle rect, int radius){var diameter = Math.Max(1, radius * 2);var path = new GraphicsPath();path.StartFigure();path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90);path.AddArc(rect.Right - diameter, rect.Y, diameter, diameter, 270, 90);path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90);path.AddArc(rect.X, rect.Bottom - diameter, diameter, diameter, 90, 90);path.CloseFigure();return path;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。