Paint a gradient color background


This article was contributed by chensu.


Have you seen an installation program that has a gradient color background? Yes, you have. How do you paint such a background?

First, you need to create a gradient color palette (CGradpalWnd::CreateGradPalette()). Then, you can paint the background with the colors in the palette (CGradpalWnd::PaintGradiantRect()).

This program allows you to paint with four directions
m_nPaintDir:
GPD_TTOB - top to bottom,
GPD_BTOT - bottom to top,
GPD_LTOR - left to right,
GPD_RTOL - right to left

and seven colors

m_nPaintRGB:
GPC_RED                          -   Red
GPC_GREEN                        -   Green
GPC_BLUE                         -   Blue
GPC_RED | GPC_GREEN              -   Yellow
GPC_RED | GPC_BLUE               -   Purple
GPC_GREEN | GPC_BLUE             -   Cyan
GPC_RED | GPC_GREEN | GPC_BLUE   -   Grey

And specify m_nPaintSteps with the number of steps it takes to paint.

Source:

// GRADPAL.H
// Written by chensu


// m_nPaintDir:
// GPD_TTOB - top to bottom,
// GPD_BTOT - bottom to top,
// GPD_LTOR - left to right,
// GPD_RTOL - right to left
#define    GPD_TTOB         0
#define    GPD_BTOT         1
#define    GPD_LTOR         2
#define    GPD_RTOL         3

// m_nPaintRGB: a combination of one or more of the following values
// i.e.:
// GPC_RED                          -   Red
// GPC_GREEN                        -   Green
// GPC_BLUE                         -   Blue
// GPC_RED | GPC_GREEN              -   Yellow
// GPC_RED | GPC_BLUE               -   Purple
// GPC_GREEN | GPC_BLUE             -   Cyan
// GPC_RED | GPC_GREEN | GPC_BLUE   -   Grey
#define    GPC_RED          0x0001
#define    GPC_GREEN        0x0002
#define    GPC_BLUE         0x0004


//-----------------------------------------------------------------------------
class CGradpalApp : public CWinApp
{
    public:
        virtual BOOL InitInstance();
};
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
class CGradpalWnd : public CFrameWnd
{
    public:
        CGradpalWnd();
        inline BOOL CreateWnd();
    
    protected:
        afx_msg BOOL OnQueryNewPalette();
        afx_msg void OnPaletteChanged(CWnd *pFocusWnd);
        afx_msg void OnPaint();
        
        DECLARE_MESSAGE_MAP()
    
    private:
        const int m_nPaintSteps, m_nPaintDir;
        const UINT m_nPaintRGB;

        CPalette m_Pal;
        
        void PaintGradiantRect(CDC *pDC, const RECT &rect) const;
        BOOL CreateGradPalette();
};
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
inline BOOL CGradpalWnd::CreateWnd()
{
    return this->Create(NULL, _T("Gradient Palette"));
}
//-----------------------------------------------------------------------------


// End of GRADPAL.H



// GRADPAL.CPP
// Written by chensu


#include <afxwin.h>
#include "gradpal.h"


//*****************************************************************************
//-----------------------------------------------------------------------------
CGradpalApp GradpalApp;
//-----------------------------------------------------------------------------
//*****************************************************************************


//*****************************************************************************
//-----------------------------------------------------------------------------
BOOL CGradpalApp::InitInstance()
{
    CGradpalWnd *pMainFrame = new CGradpalWnd();

    if (!pMainFrame->CreateWnd())
        return FALSE;

    pMainFrame->ShowWindow(m_nCmdShow);
    pMainFrame->UpdateWindow();
    
    m_pMainWnd = pMainFrame;
    
    return TRUE;
}
//-----------------------------------------------------------------------------
//*****************************************************************************


//*****************************************************************************
//-----------------------------------------------------------------------------
CGradpalWnd::CGradpalWnd() :
    m_nPaintSteps(236),     // the number of steps
    m_nPaintDir(GPD_BTOT),  // the direction
    m_nPaintRGB(GPC_BLUE)   // the color
{
    VERIFY(this->CreateGradPalette());
}
//-----------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CGradpalWnd, CFrameWnd)
    ON_WM_QUERYNEWPALETTE()
    ON_WM_PALETTECHANGED()
    ON_WM_PAINT()
END_MESSAGE_MAP()
//-----------------------------------------------------------------------------
BOOL CGradpalWnd::OnQueryNewPalette()
{
    CClientDC dc(this);
    
    CPalette *pPalOld = dc.SelectPalette(&m_Pal, FALSE);
    
    BOOL bRet = dc.RealizePalette();
    
    dc.SelectPalette(pPalOld, FALSE);
    
    if (bRet)
        // some colors changed
        this->Invalidate();
    
    return bRet;
}
//-----------------------------------------------------------------------------
void CGradpalWnd::OnPaletteChanged(CWnd *pFocusWnd)
{
    if (pFocusWnd != this)
        this->OnQueryNewPalette();
}
//-----------------------------------------------------------------------------
void CGradpalWnd::OnPaint()
{
    CPaintDC dc(this);
    
    CPalette *pPalOld = dc.SelectPalette(&m_Pal, FALSE);
    dc.RealizePalette();
    
    RECT rect;
    this->GetClientRect(&rect);
    
    this->PaintGradiantRect(&dc, rect);
    
    dc.SelectPalette(pPalOld, FALSE);
}
//-----------------------------------------------------------------------------
void CGradpalWnd::PaintGradiantRect(CDC *pDC, const RECT &rect) const
{
    ASSERT(pDC != NULL);
    ASSERT_KINDOF(CDC, pDC);
    
    // initialize
    RECT rectVar = { rect.left, rect.top, rect.left, rect.top };
    int nTotalSize;
    if (m_nPaintDir == GPD_TTOB || m_nPaintDir == GPD_BTOT)
    {
        rectVar.right = rect.right;
        nTotalSize = rect.bottom - rect.top;
    }
    else
    {
        rectVar.bottom = rect.bottom;
        nTotalSize = rect.right - rect.left;
    }
    
    // paint nSteps times
    for (int nIndex = 0; nIndex < m_nPaintSteps; nIndex++)
    {
        // calculate the rectangle
        if (m_nPaintDir == GPD_TTOB || m_nPaintDir == GPD_BTOT)
        {
            rectVar.top = rectVar.bottom;
            rectVar.bottom = rect.top +
                             ::MulDiv(nIndex + 1, nTotalSize, m_nPaintSteps);
        }
        else
        {
            rectVar.left = rectVar.right;
            rectVar.right = rect.left +
                            ::MulDiv(nIndex + 1, nTotalSize, m_nPaintSteps);
        }
        
        // calculate the color value
        int nColor = ::MulDiv(nIndex, 255, m_nPaintSteps);
        if (m_nPaintDir == GPD_BTOT || m_nPaintDir == GPD_RTOL)
            nColor = 255 - nColor;
        const COLORREF clrBr =
            PALETTERGB((BYTE)(m_nPaintRGB & GPC_RED ? nColor : 0),
                       (BYTE)(m_nPaintRGB & GPC_GREEN ? nColor : 0),
                       (BYTE)(m_nPaintRGB & GPC_BLUE ? nColor : 0));
        
        // paint the rectangle with the brush
        CBrush brush(clrBr);
        pDC->FillRect(&rectVar, &brush);
    }
}
//-----------------------------------------------------------------------------
BOOL CGradpalWnd::CreateGradPalette()
{
    if (m_Pal.GetSafeHandle() != NULL)
        return FALSE;
    
    BOOL bSucc = FALSE;
    
    const int nNumColors = 236;
    
    LPLOGPALETTE lpPal = (LPLOGPALETTE)new BYTE[sizeof(LOGPALETTE) +
                                                sizeof(PALETTEENTRY) *
                                                nNumColors];
    
    if (lpPal != NULL)
    {
        lpPal->palVersion = 0x300;
        lpPal->palNumEntries = nNumColors;
        
        PALETTEENTRY *ppe = lpPal->palPalEntry;
        
        for (int nIndex = 0; nIndex < nNumColors; nIndex++)
        {
            const int nColor = ::MulDiv(nIndex, 255, nNumColors);
            
            ppe->peRed = (BYTE)(m_nPaintRGB & GPC_RED ? nColor : 0);
            ppe->peGreen = (BYTE)(m_nPaintRGB & GPC_GREEN ? nColor : 0);
            ppe->peBlue = (BYTE)(m_nPaintRGB & GPC_BLUE ? nColor : 0);
            ppe->peFlags = (BYTE)0;
            
            ppe++;
        }
        
        bSucc = m_Pal.CreatePalette(lpPal);
        
        delete [](PBYTE)lpPal;
    }
    
    return bSucc;
}
//-----------------------------------------------------------------------------
//*****************************************************************************


// End of GRADPAL.CPP


Download sample project - 53KB


Last updated: 27 July 1998
Posted on: 19 Aug 1998



Comments

  • http://www.oakleysunglassesoutc.com/ yxjzav

    Posted by http://www.oakleysunglassesoutc.com/ Suttongqu on 03/29/2013 05:44am

    cheap ghd,The first division by train immediately east into rendezvous fourth division, form a greater pressure on the frog pond Russian second division, after receiving the news of the surrender of Shuangchengzi Russian military immediately command the first Second Division to retreat, and sent an infantry brigade to collusion. But this time Lijun Han has to give up not playing around strategic siege frog pond to the task of the Russian second division to the first division and trailing from its ghd sale formerly stationed in Kyrgyzstan Nobeoka, Karma Kazakhstan miles, rather ancient tower, Highland River Tuen, Sa Curry, Al Chu Gurkha four formal division.ghd australia,hairstraighteneraul.ghd hair straightener,com/" title="ghd hair straightener"ghd hair straightener, Railway engaged the Russian infantry brigades to reinforce its fourth division completely cut off the west do not know - and now in Russia's Far East Army telegram has been the Chinese intelligence agencies to decipher Russian troops out by telegraph every command intelligence agencies informed, and quickly passed to the front-line commanders.

    Reply
  • http://www.tomsoutletw.com/ xzqbtf

    Posted by http://www.tomsoutletw.com/ Suttonfjh on 03/28/2013 10:49am

    This beautiful lady, what you do not have the time and oakley sunglasses discount chat days? See Yakumo like this, Xiao Feng even fool knows that she is in love with himself. So playful with surprised eyes Yakumo come from the inner world of the chairs tables and refreshments, then politely the Yakumo opened a chair, a to Yakumo tea snack like. The Yakumo little hoarse voice makes Xiao Feng the Tai Sang pity, took out a retreat refining restore and regulate bodily functions role of health Dan, gently said: Yakumo believe cheap oakley sunglasses What?ray ban glasses, To eat it, you will get better together.ray ban aviators, Yakumo looked a look of gentle Xiao Feng, felt his own concern, immediately stretched out his pale face was red, and Red Eye reaching for the hands of Xiao Feng white pills.ray ban aviator sunglasses, Xiao Feng looked the shy appearance Yakumo, the wonderful girls heart heart sigh, tan greatness of love at the same time, also just a person full of resentment now become Huaichun girls.

    Reply
  • ghd australia uzgohl

    Posted by Mandybpo on 03/08/2013 04:37pm

    ghd nz snyllzmn ghd nz sale lcetrfvy ghd pfiiajfw

    Reply
  • ghd australia fdxdpv

    Posted by Suttonvtf on 02/07/2013 12:47pm

    5qFxq ugg wLao kTbr nike shox sko 7lQnc toms outlet 4xSqd hollister sale uk 9dNvb ugg 0wCac longchamp 7lYrj louis vuitton outlet 7kEea michael kors outlet 8nOvu christian louboutin 3nShu 49ers Hats 9nHcb 6wCyg 6zYbb ghd 0vEme ugg boots uk

    Reply
  • ugg boots ysodiu http://www.cheapfashionshoesas.com/

    Posted by Mandyecw on 01/29/2013 06:07pm

    8oSpi ghd eUgy Michael Kors outlet mEeu ugg boots 9xSdo ghd hair straighteners 3eDtx New York Jets Heart Soul D.Green T-Shirt Wholesale SellPhiladelphia 76ers Iguodala 9# White NBA Jerseys Wholesale SellNBA Chicago Bulls Upside Down Mesh Snapbck Wholesale SellAdidas Phoenix Suns #13 Steve Nash Purple Swingman Womens NBA Jersey Wholesale SellWashington Nationals MLB Hats Blue Red Wholesale Sell 2cWri coach,coach outlet,coach usa,coach factory outlet,coach factory 3yMjb burberry handbags 5nPin monster beats 5pLqo beats headphones 1cQrs bottes ugg pas cher 4aGvl 7oIqq 9iIzv 6aSyq 8nOrl

    Reply
  • ugg boots quyhpf http://www.cheapfashionshoesas.com/

    Posted by Mandyedo on 01/27/2013 08:23am

    3yKrb cheap nike shoes sRwl Michael Kors outlet vRpb ugg boots 6uNfc monster beats 8xCwr Cheap nfl jerseys 0wEjp ugg norge 8jEjl burberry outlet 0wPbg longchamp 3xVmy nike shoes online 3xMgu cheap uggs 8iVpd monster beats 9aOwv ugg 2hNtm GHD Australia 4zUpf 0vJyt

    Reply
  • ugg outlet store locations

    Posted by Adavollannina on 11/15/2012 09:40pm

    cadec agwya モンクレール ダウン 一覧 モンクレール moncler rodin lfuxk dcxdpm Paint a gradient color background pqmmjad ugg outlet ma uggs outlet ugg boots height irkqzsw yseun replica louis vuitton handbags new york louis vuitton belt louis vuitton outlet authentic hnvxraty beats by dre hp laptop beats dr dre cheap cheap beats by dre cable akkycgyu

    Reply
  • hndwyumw kiwyeqef pvitu http://doudouneumonclairmagasinns.blogspot.com/

    Posted by rootlyJerie on 11/13/2012 06:32pm

    vjthj lnlhp http://www.jpzpolorsrallaurenonines.info/ gjngc jlrcam Paint a gradient color background recoaqp ヴィトン バッグ airkknl ohooi doudoune moncler ulzablrz polo ralph lauren soldes imdhustv モンクレール ポロシャツ wdeunwsi

    Reply
  • http://airjordannpaschere.blogspot.com/ ubgxse zhuyrd

    Posted by emailmeshaf on 11/12/2012 11:57am

    Paint a gradient color background ucxogu htyodij zahnlx abercrombie france xuzrzyi jgomxwkd louboutin femme gzxmaln wluce sac longchamp soldes qwydqmjp sac louis vuitton bowling gdvujifg jordan pas cher pfysojnw

    Reply
  • piumini moncler blTaX abercrombie

    Posted by Foewrishrorse on 11/11/2012 02:46pm

    abercrombie pas cher ngHf0L abercrombie france akUv6G moncler rgTk1E abercrombie qkOw1J http://www.itzpiuminisoutletonlines.eu http://www.frzmdoudounesmagasinn.eu

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 16, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you starting an on-premise-to-cloud data migration project? Have you thought about how much space you might need for your online platform or how to handle data that might be related to users who no longer exist? If these questions or any other concerns have been plaguing you about your migration project, check out this eSeminar. Join our speakers Betsy Bilhorn, VP, Product Management at Scribe, Mike Virnig, PowerSucess Manager and Michele …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds