1、三角形类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; //引入此命名空间
namespace CGForm
{
class Triangle
{
PointF A, B, C;
public Triangle(PointF A, PointF B, PointF C)
{
this.A = A;
this.B = B;
this.C = C;
}
public void Draw(Graphics g)
{
Pen pen = new Pen(Color.Red, 2);
g.DrawLine(pen, A, B);
g.DrawLine(pen, B, C);
g.DrawLine(pen, C, A);
}
}
}
2、窗体类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CGForm
{
public partial class Form1 : Form
{
private Triangle t;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 绘画
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(100, 100);
t.Draw(e.Graphics);
}
/// <summary>
/// 窗体加载的时候
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
PointF A = new PointF(0, -100);
PointF B = new PointF(100, 100);
PointF C = new PointF(-100, 100);
t = new Triangle(A, B, C);
}
}
}
这里有两个函数需要注意:
1、Form1_Load和Form1_Paint,这两个函数是怎么来的,在Form中,右键属性,选择事件,然后找到Load和Paint两个事件,双击即可,出现上面两个函数。
2、在Load中,创建了一个Trianle对象
3、在Paint中进行绘制。
4、坐标的说明:
窗体的坐标是左上角为(0,0),程序中建立的点,分别为A(0,-100),B(100,100),C(-100,100),画出的三角形应该是只看到一个角而已如下图:
这里,将原点整体平移(100,100)之后:
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(100, 100);
t.Draw(e.Graphics);
}
就可看到整个三角形了: