C++--如何在Dialog和View中显示梯度背景颜色

需要达到此效果程序需要重载CWnd类的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++)
{
    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;

垂直梯度代码:
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.Height();i++)
{
    int r,g,b;
    r = r1 + (i * (r2-r1) / rect.Height());
    g = g1 + (i * (g2-g1) / rect.Height());
    b = b1 + (i * (b2-b1) / rect.Height());
    pDC->FillSolidRect(0,i,rect.Width(),1,RGB(r,g,b));
}
return true;

对角线梯度代码
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;

为了达到该目的,我们还有自建个函数MakeBitmap用于创建m_bitmap对象,该函数在OnInitDialog(Cialog)或者OnInitialUpdate(SDI)中被调用。代码如下:

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);
}

posted on 2007-08-28 14:43  毛小娃  阅读(112)  评论(0编辑  收藏  举报

导航