c# – 所有案例都涵盖了Bresenham的线算法

前端之家收集整理的这篇文章主要介绍了c# – 所有案例都涵盖了Bresenham的线算法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要检查一行中的所有像素,所以我使用Bresenham的算法来访问其中的每个像素.特别是我需要检查所有像素是否都位于位图的有效像素上.这是代码
  1. private void Bresenham(Point p1,Point p2,ref List<Point> track) {
  2. int dx = p2.X - p1.X;
  3. int dy = p2.Y - p1.Y;
  4.  
  5. int swaps = 0;
  6. if (dy > dx) {
  7. Swap(ref dx,ref dy);
  8. swaps = 1;
  9. }
  10.  
  11. int a = Math.Abs(dy);
  12. int b = -Math.Abs(dx);
  13.  
  14. double d = 2*a + b;
  15. int x = p1.X;
  16. int y = p1.Y;
  17. color_track = Color.Blue;
  18. Check_Pixel(ref area,new Point(x,y));
  19. track.Clear();
  20. track.Add(new Point(x,y));
  21.  
  22. int s = 1;
  23. int q = 1;
  24. if (p1.X > p2.X) q = -1;
  25. if (p1.Y > p2.Y) s = -1;
  26.  
  27. for(int k = 0; k < dx; k++) {
  28. if (d >= 0) {
  29. d = 2*(a+b) + d;
  30. y = y + s;
  31. x = x + q;
  32. }
  33. else {
  34. if (swaps == 1) y = y + s;
  35. else x = x + q;
  36. d = 2 * a + d;
  37. }
  38. Check_Pixel(ref area,y));
  39. track.Add(new Point(x,y));
  40. }
  41. }
  42.  
  43. private void Swap(ref int x,ref int y) {
  44. int temp = x;
  45. x = y;
  46. y = temp;
  47. }

Check_Pixel用于检查线像素是否在有效位图上.我将创建的像素添加到List< Point>逐点渲染他的元素并确保Bresenham检查正确的像素(确实如此).问题是我的算法并不涵盖所有情况,但大约有50%.

P.S:我的坐标系原点位于左上角(x从左到右,y从上到下)

解决方法

查找完整版本:
  1. public void line(int x,int y,int x2,int y2,int color) {
  2. int w = x2 - x ;
  3. int h = y2 - y ;
  4. int dx1 = 0,dy1 = 0,dx2 = 0,dy2 = 0 ;
  5. if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
  6. if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
  7. if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
  8. int longest = Math.Abs(w) ;
  9. int shortest = Math.Abs(h) ;
  10. if (!(longest>shortest)) {
  11. longest = Math.Abs(h) ;
  12. shortest = Math.Abs(w) ;
  13. if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
  14. dx2 = 0 ;
  15. }
  16. int numerator = longest >> 1 ;
  17. for (int i=0;i<=longest;i++) {
  18. putpixel(x,y,color) ;
  19. numerator += shortest ;
  20. if (!(numerator<longest)) {
  21. numerator -= longest ;
  22. x += dx1 ;
  23. y += dy1 ;
  24. } else {
  25. x += dx2 ;
  26. y += dy2 ;
  27. }
  28. }
  29. }

猜你在找的C#相关文章