- 1 year ago
Windows: Draw rectangle on camera preview
Comment
1 / 1
To draw a rectangle on a camera preview in a Windows application, you can utilize the Graphics Device Interface (GDI) to perform the drawing operations. Here's an example of how you can achieve this:
c++#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Register the window class
const wchar_t CLASS_NAME[] = L"MyWindowClass";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window
HWND hwnd = CreateWindowEx(
0, // Optional window styles
CLASS_NAME, // Window class
L"Camera Preview", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
// Show the window
ShowWindow(hwnd, nCmdShow);
// Enter the message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// Get the client area dimensions
RECT clientRect;
GetClientRect(hwnd, &clientRect);
int clientWidth = clientRect.right - clientRect.left;
int clientHeight = clientRect.bottom - clientRect.top;
// Draw the camera preview
// ...
// Draw a rectangle on the camera preview
RECT rect = { clientWidth / 4, clientHeight / 4, clientWidth * 3 / 4, clientHeight * 3 / 4 };
HBRUSH brush = CreateSolidBrush(RGB(255, 0, 0)); // Red color brush
FrameRect(hdc, &rect, brush);
DeleteObject(brush);
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
In this example:
- The
WindowProc
function handles the messages sent to the window. - The
WM_PAINT
message is handled to perform the drawing operations. - Inside the
WM_PAINT
message handler, the camera preview is drawn (replace the comment// Draw the camera preview
with your code to draw the camera preview). - After drawing the camera preview, a rectangle is drawn on top of it using the
FrameRect
function with a red color brush.
Please note that this is a basic example, and you'll need to integrate it with your camera preview code to achieve the desired result.