多边形是绘制二维、三维图形的最重要的元素之一。用C#画美国国旗代码如下:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Drawing.Drawing2D;
- namespace _005多边形
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- SetStyle(ControlStyles.ResizeRedraw, true); // 将控件设置为调整控件大小时重绘控件
- this.Width = 500;// 设置宽度
- this.Height = 310; // 设置高度
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- Graphics g = e.Graphics; // 实例化Graphics对象
- g.SmoothingMode = SmoothingMode.AntiAlias; // 对抗锯齿
- this.DrawFlag(g,20,20,this.Width - 50);
- //base.OnPaint(e);
- }
- private void DrawStar(Graphics g, float r, float xc, float yc)
- {
- // r 决定了星星的大小
- float sin36 = (float)Math.Sin(36 * Math.PI / 180.0f);
- float sin72 = (float)Math.Sin(72 * Math.PI / 180.0f);
- float cos36 = (float)Math.Cos(36 * Math.PI / 180.0f);
- float cos72 = (float)Math.Cos(72 * Math.PI / 180.0f);
- float rr1 = r * cos72 / cos36;
- // 填充星星
- PointF[] pts = new PointF[10];
- pts[0] = new PointF(xc,yc -r);
- pts[1] = new PointF(xc + r1 * sin36,yc - r1 *cos36);
- pts[2] = new PointF(xc + r * sin72,yc - r * cos72);
- pts[3] = new PointF(xc + r1 * sin72,yc + r * cos72);
- pts[4] = new PointF(xc + r * sin36,yc + r * cos36);
- pts[5] = new PointF(xc,yc + r1);
- pts[6] = new PointF(xc - r1 * sin72,yc + r * cos36);
- pts[7] = new PointF(xc - r1 * sin72,yc + r * cos72);
- pts[8] = new PointF(xc - r * sin72,yc - r * cos72);
- pts[9] = new PointF(xc - r1 * sin36,yc - r1 * cos36);
- g.FillPolygon(Brushes.White,pts);
- }
- private void DrawFlag(Graphics g, float x0, float y0, float width)
- {
- SolidBrush whiteBrush = new SolidBrush(Color.White); // 实例化白色画刷
- SolidBrush blusBrush = new SolidBrush(Color.Blue); // 实例化蓝色画刷
- SolidBrush redBrush = new SolidBrush(Color.Red); // 实例化红色画刷
- float height = 10 * width / 19;
- // 画白色矩形背景
- g.FillRectangle(whiteBrush,x0,y0,width,height);
- // 画七条红色条纹
- for (int i = 0; i < 7; i++)
- {
- g.FillRectangle(redBrush,x0,y0 +2 * i * height / 13,width,height/13);
- }
- // 画蓝色方框
- RectangleF blueBox = new RectangleF(x0,y0,2 * width / 5,7 * height / 13);
- g.FillRectangle(blusBrush,blueBox);
- // 蓝色方框内画50颗星星
- #region 把蓝色方框分成11 * 9 平方的方块,并且在每一个方块中放一个星星
- float offset = blueBox.Width / 40;
- float dx = (blueBox.Width - 2 * offset) / 11;
- float dy = (blueBox.Height - 2 * offset)/ 9;
- for (int j = 0; j < 9; j++)
- {
- float yc = y0 + offset + j * dy + dy / 2;
- for (int i = 0; i < 11; i++)
- {
- float xc = x0 + offset + i * dx + dx / 2;
- if ((i + j) %2 == 0)
- {
- DrawStar(g,this.Width / 55,xc,yc);
- }
- }
- }
- #endregion
- whiteBrush.Dispose();
- blusBrush.Dispose();
- redBrush.Dispose();
- }
- }
- }
转载于:https://blog.51cto.com/lixianhui/801772