GDI+绘制五星红旗
五星红旗是由红色背景,加5个黄色五角星组成。绘制一个五星红旗的思路,就是先定义一个五角星的自定义控件,然后通过设置五角星的大小、位置、旋转角度等属性,组合成一个五星红旗。
五角星自定义控件代码:
public partial class MyStar : Control { public MyStar() { InitializeComponent(); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); Graphics g = pe.Graphics; PointF[] points = new PointF[] { new PointF(Center.X, Center.Y - Radius), new PointF((float)(Center.X + Radius * Math.Sin(72 * Math.PI / 180)), (float)(Center.Y - Radius * Math.Cos(72 * Math.PI / 180))), new PointF((float)(Center.X + Radius * Math.Sin(36 * Math.PI / 180)), (float)(Center.Y + Radius * Math.Cos(36* Math.PI / 180))), new PointF((float)(Center.X - Radius * Math.Sin(36 * Math.PI / 180)),(float)( Center.Y + Radius * Math.Cos(36 * Math.PI / 180))),
new PointF((float)(Center.X - Radius * Math.Sin(72 * Math.PI / 180)), (float)(Center.Y - Radius * Math.Cos(72 * Math.PI / 180))), }; GraphicsPath path = new GraphicsPath(FillMode.Winding); path.AddLine(points[0], points[2]); path.AddLine(points[2], points[4]); path.AddLine(points[4], points[1]); path.AddLine(points[1], points[3]); path.AddLine(points[3], points[0]); path.CloseFigure(); g.SmoothingMode = SmoothingMode.AntiAlias; g.RotateTransform(Angle); g.FillPath(new SolidBrush(ColorTranslator.FromHtml("#FFDF00")), path); } /// <summary> /// 中心点 /// </summary> public Point Center { get; set; } /// <summary> /// 半径 /// </summary> public int Radius { get; set; } /// <summary> /// 旋转角度 /// </summary> public float Angle { get; set; } }
如上的Center、Radius、Angle都是public类型暴露出来的公共属性,以便在初始化时动态的设置MyStar相关属性。
然后创建一个窗体(450*300),并拖动一个Panel容器。
在VS中编译后会在工具栏生成MyStar控件,我们在窗体的Load事件中动态的添加MyStar控件即可。
private void Form1_Load(object sender, EventArgs e) { this.panel1.BackColor = Color.Red; MyStar c1 = new MyStar(); c1.Angle = 0F; c1.Location = new System.Drawing.Point(4, 10); c1.Size = new System.Drawing.Size(75, 75); c1.Center = new Point(50, 50); c1.Radius = 30; MyStar c2 = new MyStar(); c2.Angle = 20F; c2.Location = new System.Drawing.Point(80, -10); c2.Size = new System.Drawing.Size(40, 40); c2.Center = new Point(25, 25); c2.Radius = 10; MyStar c3 = new MyStar(); c3.Angle = -20F; c3.Location = new System.Drawing.Point(90, 30); c3.Size = new System.Drawing.Size(40, 40); c3.Center = new Point(25, 25); c3.Radius = 10; MyStar c4 = new MyStar(); c4.Angle = 0F; c4.Location = new System.Drawing.Point(98, 55); c4.Size = new System.Drawing.Size(40, 40); c4.Center = new Point(25, 25); c4.Radius = 10; MyStar c5 = new MyStar(); c5.Angle = 20F; c5.Location = new System.Drawing.Point(80, 70); c5.Size = new System.Drawing.Size(40, 40); c5.Center = new Point(25, 25); c5.Radius = 10; this.panel1.Controls.Add(c1); this.panel1.Controls.Add(c2); this.panel1.Controls.Add(c3); this.panel1.Controls.Add(c4); this.panel1.Controls.Add(c5); this.panel1.Click += (ss, ee) => { this.Close(); }; }
效果图: