65.9K
CodeProject 正在变化。 阅读更多。
Home

在 Win32/SDK 程序中使用颜色渐变

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.22/5 (8投票s)

2002年10月13日

1分钟阅读

viewsIcon

98978

如何在 SDK 应用程序中创建一个颜色渐变作为背景。

Sample Image - grad.jpg

引言

创建一个颜色渐变作为背景并不难。 如果你阅读过 Nishant 关于在 MFC 中使用颜色渐变的的文章,那么这段代码只是他文章的一个修改过的 SDK 版本。

深入了解

好的,首先我建议阅读 MFC 版本

在那之后,你应该对它是如何完成的有一个简单的理解。 要开始,只需将 WM_ERASEBKGND 消息添加到你的窗口过程函数中。 我建议创建一个单独的函数来完成实际绘制背景的所有工作。 如果你决定采取这种方法,请确保在函数的声明中传递你的主窗口的句柄。 这样说来,现在是代码的时候了。

void OnEraseBkGnd(HWND hwnd)
{
    /* Vars */
    HDC dc; /* Standard Device Context; used to do the painting */
    
    /* rect = Client Rect of the window; 
    Temp = Temparory rect tangle for the color bands */
    RECT rect, temp; 
    HBRUSH color; /* A brush to do the painting with */
    
    /* Get the dc for the wnd */
    dc = GetDC(hwnd);
    
    /* Get the client rect */
    GetClientRect(hwnd, &rect);
    
    /* Start color; Change the R,G,B values 
    to the color of your choice */
    int r1 = 255, g1 = 0, b1 = 0;
    
    /* End Color; Change the R,G,B values 
    to the color of your choice */
    int r2 = 255, g2 = 255, b2 = 0;
    
    /* loop to create the gradient */
    for(int i=0;i<rect.right;i++) 
    { 
        /* Color ref. for the gradient */
        int r,g,b; 
        /* Determine the colors */
        r = r1 + (i * (r2-r1) / rect.right); 
        g = g1 + (i * (g2-g1) / rect.right);
        b = b1 + (i * (b2-b1) / rect.right);
        
        /* Fill in the rectangle information */
        
        /* The uper left point of the rectangle 
        being painted; uses i as the starting point*/
        temp.left = i;
        /* Upeer Y cord. Always start at the top */ 
        temp.top = 0; 
        /* Okay heres the key part, 
        create a rectangle thats 1 pixel wide */
        temp.right = i + 1; 
        /* Height of the rectangle */
        temp.bottom = rect.bottom; 
        
        /* Create a brush to draw with; 
        these colors are randomized */
        color = CreateSolidBrush(RGB(r, g, b));
        
        /* Finally fill in the rectangle */
        FillRect(dc, &temp, color);
    }
}

最终注释

最后一点,现在这并不难,是吗? 创建渐变真的很容易。 另外,如果你为创建渐变创建了第二个函数,你可以很容易地在想要渐变出现时调用该函数。 此外,通过进行一些自定义,你可以很容易地使渐变仅为窗口的一部分。 好了,就这样了…

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.