中点Brehensam画线算法
1 #include<stdio.h> 2 3 #include<stdlib.h> 4 5 #include"graphics.h" 6 7 8 9 //函数声明 10 11 void MidBrehansem(int x0, int y0, int x1, int y1); //中点MidBrehansem算法 12 13 void swap(int &x, int &y); //利用引用传递交换值 14 15 16 17 int main() 18 19 { 20 21 int gdriver = DETECT, gmode; 22 23 int x0, y0, x1, y1; 24 25 26 27 printf("Please input start point:\n"); 28 29 scanf("%d%d", &x0, &y0); 30 31 printf("Please input end point:\n"); 32 33 scanf("%d%d", &x1, &y1); 34 35 36 37 initgraph(&gdriver, &gmode, ""); 38 39 40 41 MidBrehansem(x0, y0, x1, y1); 42 43 44 45 system("pause"); 46 47 48 49 closegraph(); 50 51 52 53 return 0; 54 55 } 56 57 58 59 //中点MidBrehansem算法 60 61 void MidBrehansem(int x0, int y0, int x1, int y1) 62 63 { 64 65 int dx, dy,i,di; 66 67 double k; 68 69 70 71 if (x0 > x1) 72 73 { 74 75 swap(x0, x1); 76 77 swap(y0, y1); 78 79 } 80 81 82 83 int x = x0, y = y0; //定义到前面会从x1,y1开始画线 84 85 86 87 dx = x1 - x0; 88 89 dy = y1 - y0; 90 91 92 93 k = 1.0*dy / dx; 94 95 i = (abs(dy)>abs(dx)) ? abs(dy): abs(dx); 96 97 98 99 if (k >= 1) 100 101 { 102 103 di = 2 * dx + dy; 104 105 while (i--) 106 107 { 108 109 putpixel(x, y, RED); 110 111 if (di >= 0) 112 113 { 114 115 di += 2 * (dx - dy); 116 117 x++; 118 119 } 120 121 else 122 123 di += 2 * dx; 124 125 126 127 y++; 128 129 } 130 131 } 132 133 else if (k >= 0 && k < 1) 134 135 { 136 137 di = dx - 2 * dy; 138 139 while (i--) 140 141 { 142 143 putpixel(x, y, YELLOW); 144 145 if (di < 0) 146 147 { 148 149 di += 2 * (dx - dy); 150 151 y++; 152 153 } 154 155 else 156 157 di += (-2)*dy; 158 159 160 161 x++; 162 163 } 164 165 } 166 167 else if (k >= -1 && k < 0) 168 169 { 170 171 di = -dx - 2 * dy; 172 173 while (i--) 174 175 { 176 177 putpixel(x, y, YELLOW); 178 179 if (di >= 0) 180 181 { 182 183 di += (-2)*(dx + dy); 184 185 y--; 186 187 } 188 189 else 190 191 di += (-2)*dy; 192 193 194 195 x++; 196 197 } 198 199 } 200 201 else 202 203 { 204 205 di = -2 * (dx + dy); 206 207 while (i--) 208 209 { 210 211 putpixel(x, y, WHITE); 212 213 if (di < 0) 214 215 { 216 217 di += (-2)*(dx + dy); 218 219 x++; 220 221 } 222 223 else 224 225 di += (-2)*dx; 226 227 228 229 y--; 230 231 } 232 233 } 234 235 236 237 } 238 239 240 241 //利用引用传递交换值 242 243 void swap(int &x, int &y) 244 245 { 246 247 int t; 248 249 250 251 t = x; 252 253 x = y; 254 255 y = t; 256 257 }