画时钟表盘c语言
时间: 2023-07-03 08:23:24 浏览: 149
下面是一个简单的 C 语言时钟表盘的示例代码,使用了 Windows API 的 GDI 绘图功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define WINDOW_WIDTH 400
#define WINDOW_HEIGHT 400
#define PI 3.1415926
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = "ClockWindowClass";
wc.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wc);
HWND hwnd = CreateWindow("ClockWindowClass", "时钟表盘", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static int cxClient, cyClient;
switch (message) {
case WM_SIZE:
cxClient = LOWORD(lParam);
cyClient = HIWORD(lParam);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// 绘制表盘
HPEN pen = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
HPEN oldPen = (HPEN)SelectObject(hdc, pen);
HBRUSH brush = CreateSolidBrush(RGB(255, 255, 255));
HBRUSH oldBrush = (HBRUSH)SelectObject(hdc, brush);
Ellipse(hdc, 50, 50, cxClient - 50, cyClient - 50);
SelectObject(hdc, oldPen);
DeleteObject(pen);
SelectObject(hdc, oldBrush);
DeleteObject(brush);
// 绘制刻度
double radius = (cxClient - 100) / 2.0;
int centerX = cxClient / 2;
int centerY = cyClient / 2;
for (int i = 0; i < 12; i++) {
double angle = i * PI / 6.0;
int x1 = (int)(centerX + (radius - 20) * cos(angle));
int y1 = (int)(centerY - (radius - 20) * sin(angle));
int x2 = (int)(centerX + radius * cos(angle));
int y2 = (int)(centerY - radius * sin(angle));
MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, x2, y2);
}
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
```
这个程序使用了 Windows API 来创建一个窗口,并在窗口中绘制了一个简单的时钟表盘。程序主要的代码在 WM_PAINT 事件处理中,首先绘制了一个白色的圆形表盘,然后在表盘上绘制了 12 条刻度线,每条刻度线之间相隔 30 度,最后使用 EndPaint 函数结束绘制。
阅读全文