Tree branch
Another tree branch
OpenGL Tutorials
Spider web
Facebook Twitter Google Plus
How To Draw Pixels in A Window Using GDI (Graphics Device Interface)

In the previous tutorial you learned how to create a window on the screen and wrote a message loop system. In this tutorial you'll learn how to draw some pixels inside the window you created.

I can already tell that this is going to be a short tutorial but it gives you the basics of drawing in a window. I'll take the windows program from the previous tutorial and for this tutorial most of the code will be located inside the message loop.

To start drawing anything in a window you will need to obtain a copy of its device context. And after you're done drawing you have to release the device context. You can do that with the following two calls:

// Get DC HDC hdc = GetDC(hwnd); // Release DC ReleaseDC(hwnd, hdc);

The code for drawing pixels doesn't require rocket science knowledge. To draw a pixel on the screen you have to call SetPixel and pass the location of the pixel in window coordinates, its color and the DC. I'll insert the pixel drawing code into the previous tutorial's base code inside the message loop.

// The message loop HDC hdc = GetDC(hwnd); while(!quit) { if(PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { if(msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } for(int i = 0; i < 1000; i++) { int x = rand()%300; int y = rand()%300; SetPixel(hdc, x, y, RGB(rand()%255, 0, 0)); } } ReleaseDC(hwnd, hdc);

This code will draw 1000 randomly shaded and positioned pixels inside the window each frame. Find out how to draw lines, circles and rectangles by snooping through the MSDN help files. I did. It's a good practice. Or otherwise, if anyone feels really lost, you can send me a tutorial request.

© 2014 OpenGL Tutorials.

About | Privacy | Contact

Built with Tornado PHP FrameworkTornado PHP Framework with Wooden PHP Template template | Web design by Web Design by Greg.