笔连接样式未应用于形状的所有角落

时间:2016-03-15 15:26:33

标签: c winapi gdi

Line joins

使用Polyline()函数绘制形状。 相关代码在这里:

void DoDrawing(HWND hwnd) {

    LOGBRUSH brush;
    COLORREF col = RGB(0, 0, 0);
    DWORD pen_style = PS_SOLID | PS_JOIN_MITER | PS_GEOMETRIC;

    brush.lbStyle = BS_SOLID;
    brush.lbColor = col;
    brush.lbHatch = 0;       

    PAINTSTRUCT ps;

    HDC hdc = BeginPaint(hwnd, &ps);

    HPEN hPen1 = ExtCreatePen(pen_style, 8, &brush, 0, NULL);
    HPEN holdPen = SelectObject(hdc, hPen1);

    POINT points[5] = { { 10, 30 }, { 100, 30 }, { 100, 100 }, { 10, 100 }, {10, 30}};
    Polyline(hdc, points, 5);
    DeleteObject(hPen1);

    SelectObject(hdc, holdPen);

    EndPaint(hwnd, &ps);  
}

PS_JOIN_MITER应用于三个角但不在左上角。在该角落,使用默认的PS_JOIN_ROUND。如何解决这个问题?

以下是一个完整的工作示例:

#include <windows.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void DoDrawing(HWND);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    PWSTR lpCmdLine, int nCmdShow) {

    MSG  msg;
    WNDCLASSW wc = {0};

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpszClassName = L"Pens";
    wc.hInstance     = hInstance;
    wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpfnWndProc   = WndProc;
    wc.hCursor       = LoadCursor(0, IDC_ARROW);

    RegisterClassW(&wc);
    CreateWindowW(wc.lpszClassName, L"Line joins",
          WS_OVERLAPPEDWINDOW | WS_VISIBLE,
          100, 100, 250, 180, NULL, NULL, hInstance, NULL);

    while (GetMessage(&msg, NULL, 0, 0)) {

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

  return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam) {

    switch(msg) {

        case WM_PAINT:

            DoDrawing(hwnd);
            break;

        case WM_DESTROY:

            PostQuitMessage(0);
            return 0;
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void DoDrawing(HWND hwnd) {

    LOGBRUSH brush;
    COLORREF col = RGB(0, 0, 0);
    DWORD pen_style = PS_SOLID | PS_JOIN_MITER | PS_GEOMETRIC;

    brush.lbStyle = BS_SOLID;
    brush.lbColor = col;
    brush.lbHatch = 0;       

    PAINTSTRUCT ps;

    HDC hdc = BeginPaint(hwnd, &ps);

    HPEN hPen1 = ExtCreatePen(pen_style, 8, &brush, 0, NULL);
    HPEN holdPen = SelectObject(hdc, hPen1);

    POINT points[5] = { { 10, 30 }, { 100, 30 }, { 100, 100 }, { 10, 100 }, {10, 30}};
    Polyline(hdc, points, 5);
    DeleteObject(hPen1);

    SelectObject(hdc, holdPen);

    EndPaint(hwnd, &ps);  
}

1 个答案:

答案 0 :(得分:1)

Polyline没有加入第一点和最后一点。

使用Polygon(hdc, points, 5)代替Polyline

此外,在删除现有笔之前,请按以下顺序选择oldPen到DC:

SelectObject(hdc, holdPen);
DeleteObject(hPen1);

(如果你不按正确的顺序执行,Windows会原谅你)