所有案例都涵盖了布雷森汉姆的线算法 [英] All cases covered Bresenham's line-algorithm

查看:98
本文介绍了所有案例都涵盖了布雷森汉姆的线算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一行中的所有像素,因此我正在使用Bresenham的算法来访问其中的每个像素.特别是,我需要检查所有像素是否都位于位图的有效像素上.这是代码:

I need to check all pixels in a line, so I'm using Bresenham's algorithm to access each pixel in it. In particular I need to check if all pixels are located on valid pixel of a bitmap. This is the code:

private void Bresenham(Point p1, Point p2, ref List<Point> track) {
  int dx = p2.X - p1.X;
  int dy = p2.Y - p1.Y;

  int swaps = 0;
  if (dy > dx) {
    Swap(ref dx, ref dy);
    swaps = 1;
  }

  int a = Math.Abs(dy);
  int b = -Math.Abs(dx);

  double d = 2*a + b;
  int x = p1.X;
  int y = p1.Y;
  color_track = Color.Blue;
  Check_Pixel(ref area, new Point(x,y));
  track.Clear();
  track.Add(new Point(x, y));

  int s = 1;
  int q = 1;
  if (p1.X > p2.X) q = -1;
  if (p1.Y > p2.Y) s = -1;

  for(int k = 0; k < dx; k++) {
    if (d >= 0) {
      d = 2*(a+b) + d;
      y = y + s;
      x = x + q;
    }
    else {
      if (swaps == 1) y = y + s;
      else x = x + q;
      d = 2 * a + d;
    }
    Check_Pixel(ref area, new Point(x, y));
    track.Add(new Point(x, y));
  }
}

private void Swap(ref int x, ref int y) {
  int temp = x;
  x = y;
  y = temp;
}

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

Check_Pixel is used to check if the line pixel is on a valid bitmap one. I add the pixel founded to a List<Point> to render point by point his element and be sure Bresenham checks the correct pixels (it does). The problem is that my algorithm doesn't cover all the cases but about 50% of them.

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

P.S: my coordinates system origin is on the left-upper corner (x grows left to right, y up to down)

推荐答案

查找完整版本:

public void line(int x,int y,int x2, int y2, int color) {
    int w = x2 - x ;
    int h = y2 - y ;
    int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
    if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
    if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
    if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
    int longest = Math.Abs(w) ;
    int shortest = Math.Abs(h) ;
    if (!(longest>shortest)) {
        longest = Math.Abs(h) ;
        shortest = Math.Abs(w) ;
        if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
        dx2 = 0 ;            
    }
    int numerator = longest >> 1 ;
    for (int i=0;i<=longest;i++) {
        putpixel(x,y,color) ;
        numerator += shortest ;
        if (!(numerator<longest)) {
            numerator -= longest ;
            x += dx1 ;
            y += dy1 ;
        } else {
            x += dx2 ;
            y += dy2 ;
        }
    }
}

这篇关于所有案例都涵盖了布雷森汉姆的线算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆