实现背景颜色的渐变效果(code project)

如果只是实现水平或垂直方向的背景色渐变,只需重载OnEraseBkgnd函数,具体代码如下:CDialog::OnEraseBkgnd(pDC);

CRect rect;
GetClientRect(&rect);

int r1=127,g1=127,b1=56; //Any start color
int r2=5,g2=55,b2=165; //Any stop color

for(int i=0;i<rect.Width();i++)    //如果是垂直方向则rect.Height(),下同
{
    int r,g,b;
    r = r1 + (i * (r2-r1) / rect.Width());
    g = g1 + (i * (g2-g1) / rect.Width());
    b = b1 + (i * (b2-b1) / rect.Width());
    pDC->FillSolidRect(i,0,1,rect.Height(),RGB(r,g,b));
}

return true;

如果要实现倾斜的渐变,需要加一函数,同时在OnInitDialog中调用

CDialog::OnEraseBkgnd(pDC);

CRect rect;
GetClientRect(&rect);

CDC dc2;
dc2.CreateCompatibleDC(pDC);
CBitmap *oldbmap=dc2.SelectObject(&m_bitmap);

/*We copy the bitmap into the DC*/
pDC->BitBlt(0,0,rect.Width(),rect.Height(),&dc2,0,0,SRCCOPY);
dc2.SelectObject(oldbmap);

return true;

void CYourClassName::MakeBitmap()
{
    CPaintDC dc(this);
    CRect rect;
    GetClientRect(&rect);

    int r1=245,g1=190,b1=240;
    int r2=130,g2=0,b2=0;

    int x1=0,y1=0;
    int x2=0,y2=0;

    CDC dc2;
    dc2.CreateCompatibleDC(&dc);

    if(m_bitmap.m_hObject)
        m_bitmap.DeleteObject();
    m_bitmap.CreateCompatibleBitmap(&dc,rect.Width(),
        rect.Height());

    CBitmap *oldbmap=dc2.SelectObject(&m_bitmap);

    while(x1 < rect.Width() && y1 < rect.Height())
    {
        if(y1 < rect.Height()-1)
            y1++;
        else
            x1++;

        if(x2 < rect.Width()-1)
            x2++;
        else
            y2++;

        int r,g,b;
        int i = x1+y1;
        r = r1 + (i * (r2-r1) / (rect.Width()+rect.Height()));
        g = g1 + (i * (g2-g1) / (rect.Width()+rect.Height()));
        b = b1 + (i * (b2-b1) / (rect.Width()+rect.Height()));

        CPen p(PS_SOLID,1,RGB(r,g,b));
        CPen *oldpen = dc2.SelectObject(&p);

        dc2.MoveTo(x1,y1);
        dc2.LineTo(x2,y2);

        dc2.SelectObject(oldpen);
    }

    dc2.SelectObject(oldbmap);

}

你可能感兴趣的:(实现背景颜色的渐变效果(code project))