Search code examples
visual-studio-2015mfcondrawsdi

drawing square net in SDI MFC


how can i draw square net ( like chess) in SDI MFC ? and how to determine the position for putting some more shape in specific position ? i have to use (Moveto) and (Lineto) and draw them 1 by 1 ? or using bitmap ? or easier way ? i tried in this way but it's not really smart. thank you.

COLORREF blueline = RGB(255, 0, 0);
    pen1.CreatePen(PS_SOLID, 3, blueline);
    pDC->SelectObject(&pen1);
    pDC->MoveTo(0,80);
    pDC->LineTo(1024, 80);
    pDC->SelectObject(&pen1);

Solution

  • You can draw solid rectangles by calling CDC::FillSolidRect. If your rectangles should contain a more complex pattern, use CDC::FillRect instead.

    You can render a checkered board using the following pseudo-code:

    for (int x = 0; x < 8; ++x) {
        for (int y = 0; y < 8; ++y ) {
            // Calculate square position and size
            int x0 = x_origin + x * square_width;
            int x1 = x_origin + (x + 1) * square_width;
            int y0 = y_origin + y * square_height;
            int y1 = y_origin + (y + 1) * square_height;
            RECT r = {x0, y0, x1, y1};
            // Pick alternating color
            COLORREF color = (x + y) & 1 ? RGB(0, 0, 0) : RGB(255, 255, 255);
            // Render square
            pDC->FillSolidRect(&r, color);
        }
    }