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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值