举报

用窗口HDC执行GDI函数时绘图错误

0

EasyX的在线文档说GetImageHDC的参数为NULL时,表示获取默认绘图窗口的HDC句柄。下面的代码用GDI的SetPixel函数来测试,但有些地方会变成黑色的:

// 编译环境:Visual Studio 2013, EasyX_26.1.1

#include "easyx.h"
#include <conio.h>

void RGBCube(HDC hDC)
{
	int r, g, b;

	// draw and label axes

	// Red = 0xFF
	for (g=0; g<256; g++/*, Sleep(1)*/)
	for (b=0; b<256; b++)
		SetPixel(hDC, g, 383-b, RGB(0xFF, g, b));
	// Blue = 0xFF, top, sheared
	for (g=0; g<256; g++/*, Sleep(1)*/)
	for (r=0; r<256; r+=2)
		SetPixel(hDC, g+128-r/2, r/2, RGB(r, g, 0xFF));

	// Green = 0xFF, right, sheared
	for (b=0; b<256; b++/*, Sleep(1)*/)
	for (r=0; r<256; r+=2)
		SetPixel(hDC, 383-r/2, 255+r/2-b, RGB(r, 0xFF, b));
}

int main()
{
	initgraph(384, 384);
	MessageBox(GetHWnd(), GetEasyXVer(), TEXT("Version"), MB_OK);
	RGBCube(GetImageHDC());
	FlushBatchDraw();
	_getch();
	return 0;
}

加上Sleep(1)的延时就更明显了:截图

用EasyX_2018春分版编译的话,在绘图的时候不停地将窗口拖到屏幕外然后再拖回来,有可能变成这样:截图

ava
张书睿

2026-3-9

举报
0

setpixel 效率极低,应该使用内存位图,或者 easyx 的缓存指针 GetImageBuffer 绘制像素点

// 编译环境:Visual Studio 2013, EasyX_26.1.1

#include "easyx.h"
#include <conio.h>

void RGBCube(HDC hDC)
{
    HDC hdcMem = CreateCompatibleDC(hDC);
    HBITMAP hBmp = CreateCompatibleBitmap(hDC, 384, 384);
    HBITMAP hOldBmp = (HBITMAP)SelectObject(hdcMem, hBmp);

    DWORD* pPixels = new DWORD[384 * 384];
	for (int y = 128; y < 384; y++)
		for (int x = 0; x < 256; x++) {
            pPixels[y * 384 + x] = RGB(0xFF, y - 128, x);
		}

    BITMAPINFO bmi = { 0 };
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = 384;
    bmi.bmiHeader.biBitCount = 32;
    bmi.bmiHeader.biHeight = -384;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biCompression = BI_RGB;
    SetDIBits(hdcMem, hBmp, 0, 384, pPixels, &bmi, DIB_RGB_COLORS);
    BitBlt(hDC, 0, 0, 384, 384, hdcMem, 0, 0, SRCCOPY);

    delete[] pPixels;
    SelectObject(hdcMem, hOldBmp);
    DeleteObject(hBmp);
    DeleteDC(hdcMem);
    ReleaseDC(NULL, hDC);

}

int main()
{
	initgraph(384, 384);
	RGBCube(GetImageHDC());
	_getch();
	return 0;
}
ava
xiongfj ◑◑

2026-3-17

技术讨论社区