如何画一条线并用 C# 将其转换为直线? [关闭]

问题描述 投票:0回答:1

如何绘制一条线并用 C# 将其转换为直线?

像这样

c# bitmap draw paint windows-forms-core
1个回答
0
投票

你可以得到曲线的第一个像素的y坐标,然后遍历所有像素并将它们的y坐标设置为这个值。

要找到一行的开头,您可以遍历位图像素,直到找到只有 1 个相邻像素为黑色的像素(假设位图由白色/黑色像素组成)。

// Retrieve the image.
image1 = new Bitmap(@"\\ path \ to \ file.bmp", true);

int x, y;
int yLevel = -1; // use for straight line

// Loop through the images pixels to get start of line
for(x=0; x < image1.Width; x++) {
  for(y=0; y < image1.Height; y++) {
    Color pixelColor = image1.GetPixel(x, y);
    if (pixelColor != Color.Black) continue;
    
    int blackNeighbors = 0;
    
    if(image1.GetPixel(x-1,y-1) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x-1,y) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x-1,y+1) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x,y-1) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x,y+1) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x+1,y+1) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x+1,y) == Color.Black) { 
      blackNeighbors++;
    }
    if(image1.GetPixel(x+1,y-1) == Color.Black) { 
      blackNeighbors++;
    }
    
    if(blackNeighbors == 1) {
      yLevel = y;
      break;
    }
  }
  if (yLevel != -1) {
    break;
  }
}



// Loop through the images pixels to straighten line
for(x=0; x < image1.Width; x++) {
  for(y=0; y < image1.Height; y++) {
    Color pixelColor = image1.GetPixel(x, y);
    if (pixelColor == Color.Black && y != yLevel) {
      image1.SetPixel(x, y, Color.White);
      image1.SetPixel(x, yLevel, Color.Black);
    }
  }
}

// Set the PictureBox to display the image.
PictureBox1.Image = image1;

© www.soinside.com 2019 - 2024. All rights reserved.