Search code examples
c++mathdrawinglinesdiagonal

Manipulating a diagonal line in C++


I am playing with using nested for-loops to plot pixels and basically draw flags. So far I've figured out how to make circles, diagonal lines and crosses.

I am however not able to wrap my head around how to limit from where a straight line is to be drawn.

Basically I'm trying to figure out how I need to change the code I used to draw the diagonal lines in the union jack to make the swastika in the flag of nazi Germany. Any help would be much appreciated!

Here's my current code and a screenshot of what I get:

for (int x = 0; x < 240; x++)
{
    for (int y = 0; y < 160; y++)
    {
        uint16_t cX = 120;
        uint16_t cY = 80;
        uint16_t r = 66;

        // Makes line
        if (x-100 < y * 240 / 240 + 20 && x-100 > y * 240 / 240 - 20)
        {
            PlotPixel16(x, y, black);
        }
// Makes circle
        else if (((x-cX)*(x-cX))+((y-cY)*(y-cY)) < r*r)
        {
            PlotPixel16(x, y, white);
        }
        else
        {
            PlotPixel16(x, y, red);
        }
    }
}

Screenshot!


Solution

  • You're actually drawing a polygon defined by four lines. The equation of a line is y=mx+b, and you want to be either above or below the line. While this isn't how I would do it, it's keeping with the spirit of your approach to test that y-mx+b<0 (or >0) for four different pairs of m and b. That will give you one line segment, and you can get the rest similarly.

    Right now, you're selecting a region between only two lines. That's why you're getting that image.