How to display pixels on a screen directly from a raw array of RGB values ​​faster than SetPixel ()?

I like to create “animations” in C ++, such as the MandelBrot Set scaling device, the Game of Life simulator, etc., setting pixels directly onto the screen frame by frame. The SetPixel () command makes this incredibly simple, although unfortunately it is also very slow. Here is the setting that I use for each frame if I wanted to draw a full screen with the contents of the R array:

#include <windows.h> using namespace std; int main() { int xres = 1366; int yres = 768; char *R = new char [xres*yres*3]; /* R is a char array containing the RGB value of each pixel sequentially Arithmetic operations done to each element of R here */ HWND window; HDC dc; window = GetActiveWindow(); dc = GetDC(window); for (int j=0 ; j<yres ; j++) for (int i=0 ; i<xres ; i++) SetPixel(dc,i,j,RGB(R[j*xres+3*i],R[j*xres+3*i+1],R[j*xres+3*i+2])); delete [] R; return 0; } 

On my machine, it takes almost 5 seconds to execute for the obvious reason that SetPixel () is called more than a million times. The best scenario for the case, I could make it work 100 times faster and get a smooth animation of 20 frames per second.

I heard that converting R to a raster file in some way and then using BitBlt to display the frame in one clean command is the way to go, but I don’t know how to implement this for my installation, and I really appreciate the help.

If relevant, I launch Windows 7 and use Code :: Blocks as my IDE.

+8
c ++ windows pixel animation bitmap
source share
1 answer

Following Remy's recommendations, I ended up this way of displaying an array of pixels (for guys who need sample code):

 COLORREF *arr = (COLORREF*) calloc(512*512, sizeof(COLORREF)); /* Filling array here */ /* ... */ // Creating temp bitmap HBITMAP map = CreateBitmap(512 // width. 512 in my case 512, // height 1, // Color Planes, unfortanutelly don't know what is it actually. Let it be 1 8*4, // Size of memory for one pixel in bits (in win32 4 bytes = 4*8 bits) (void*) arr); // pointer to array // Temp HDC to copy picture HDC src = CreateCompatibleDC(hdc); // hdc - Device context for window, I've got earlier with GetDC(hWnd) or GetDC(NULL); SelectObject(src, map); // Inserting picture into our temp HDC // Copy image from temp HDC to window BitBlt(hdc, // Destination 10, // x and 10, // y - upper-left corner of place, where we'd like to copy 512, // width of the region 512, // height src, // source 0, // x and 0, // y of upper left corner of part of the source, from where we'd like to copy SRCCOPY); // Defined DWORD to juct copy pixels. Watch more on msdn; DeleteDC(src); // Deleting temp HDC 
+7
source share

All Articles