如何使用 C 在位图图像上创建对角线

How to create a diagonal line on bitmap image with C

如何用C画对角线,我想得到四个坐标,画出最完美的对角线,但是我想一个像素一个像素画。问题是当图像不是“正方形”时,我不知道该怎么做。

我目前的情况:

// try one
    for (int i = ystart, j = xstart; i < yend && j < xend; i++, j++)
    {
        printf("%d ", distance);
        image[i][j].rgbtRed = 255;
        image[i][j].rgbtGreen = 255;
        image[i][j].rgbtBlue = 255;
    }

// try two
    int distance = sqrt(pow(xend - xstart, 2) + pow(yend - ystart, 2));

    for (int w = 0, i = ystart, j = xstart; w < distance; w++)
    {
        image[i][j].rgbtRed = 255;
        image[i][j].rgbtGreen = 255;
        image[i][j].rgbtBlue = 255;

        i++;
        j++;

        if (i > yend - 1 || j > xend - 1)
        {
            break;
        }
    }


// I also have a two-dimensional (the image) array and width and height of the image, the image I'm using is 600x400, completely black and I want a diagonal line based on the parameters of the function

使用 middle-school 代数 class 中的直线公式,“y = mx + b”,并计算每个 x 的理想 y。

要从 (1, 7) 到 (6, 10) 画一条线,您可以这样做:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

void draw_pixel (int x, int y) {
  printf("draw pixel at (%d, %d)\n", x, y);
};

void main () {

  float m = (float) (10 - 7) / (6 - 1);

  float y = 7;
  for (int x = 1; x <= 6; x++) {
    draw_pixel(x, (int) round(y));
    y += m;
  };

};

这是做什么的:

draw pixel at (1, 7)
draw pixel at (2, 8)
draw pixel at (3, 8)
draw pixel at (4, 9)
draw pixel at (5, 9)
draw pixel at (6, 10)

您会注意到,在 abs(x2 - x1) < abs(y2 - y1) 时效果不佳,因为它不会绘制一条连续的线。要解决这个问题,您必须使用不同的公式 x = my + b,它以相同的方式完成,但通过交换每个 x 和 y 值,以便 for() 循环遍历每个 y 值并计算x,而不是遍历每个 x 值并计算 y。

使用天真的 line-drawing 算法绘制它,使用 cartesian formula 作为平面中的一条线看起来不太好:

dx = x2 − x1
dy = y2 − y1
for x from x1 to x2 do
    y = y1 + dy*(x − x1)/dx
    matrix[x, y] = BLACK

想做功课可以,做个好软件不行。在过去,对于旧的显示器,这是一个问题。很难制作一个程序来绘制一条像线一样可见的线。

有很多algorithms可以做到。