《计算机图形技术》练习--用GDI+模拟DDA算法

刘义军老师留的作业

代码简单,一看就懂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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;

namespace GDI_DDA
{
public partial class Form1 : Form
{
int pointSize = 22;
int width = Screen.PrimaryScreen.WorkingArea.Width;
int height = Screen.PrimaryScreen.WorkingArea.Height;

public Form1()
{
InitializeComponent();
}

void DrawGrid(Graphics gra)
{
for (int i = 0; i <= Width; i += pointSize)
{
gra.DrawLine(Pens.Black, i, 0, i, height);
}

for (int i = 0; i <= height; i += pointSize)
{
gra.DrawLine(Pens.Black, 0, i, Width, i);
}
}

void MyDrawLine(Graphics gra, float startX, float startY, float endX, float endY)
{
float dx = endX - startX;
float dy = endY - startY;
float delta = dy / dx;
float
y = startY;
for (int x = (int) startX; x <= endX; x++, y += delta)
{
DrawEllipseByCenter(gra, Pens.Red, x * pointSize, y * pointSize, pointSize * 0.5f);
}
}

void DrawEllipseByCenter(Graphics g, Pen p, float centerX, float centerY, float r)
{
g.FillEllipse(Brushes.Red, centerX - r * 0.5f, centerY - 0.5f, 2 * r, 2 * r);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics myGra = e.Graphics;
DrawGrid(myGra);
MyDrawLine(myGra, 3, 5, 47, 25);
myGra.DrawLine(Pens.Red, 3 * pointSize, 5 * pointSize, 47 * pointSize, 25 * pointSize);
myGra.Dispose();
}
}
}