Click here to Skip to main content
6,595,854 members and growing! (17,388 online)
Email Password   helpLost your password?
Desktop Development » Button Controls » Non-rectangular Buttons     Intermediate License: The Code Project Open License (CPOL)

Transparent Button with Region and Anti-Aliased Edges

By Bob Carboni

Code for creating transparent, blended bitmapped buttons.
VC6Win2K, WinXP, MFC, GDI, Dev
Posted:10 Aug 2004
Updated:16 Aug 2004
Views:160,156
Bookmarked:111 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
41 votes for this article.
Popularity: 7.44 Rating: 4.61 out of 5
1 vote, 2.4%
1

2
2 votes, 4.9%
3
3 votes, 7.3%
4
35 votes, 85.4%
5

Sample Image - TransButtonDemo.jpg

Introduction

This is an example of how to create and use masked and semi-transparent bitmap buttons that can be overlaid on any background, including other bitmaps. The buttons are automatically alpha-blended (anti-aliased) with the background to create nice smooth edges, and provide region clipping to create various elliptical and other shapes.

Instead of creating a new class that duplicates all the other functionality of owner-draw buttons, the code to draw the transparency and create regions was added to the CHoverButtonEx class written by Niek Albers and modified by Frederick Ackers. If you are already using the CHoverButtonEx class, you can simply replace it with this version without affecting existing functionality, although I have also added a fourth image to the bitmaps for a disabled view, so you would need this image in your existing bitmaps, or you would need to change the references back to 3.

The demo project uses a dialog-based regioned window that displays a circular, patterned bitmap as the background. This type of bitmapped background shows how these buttons can take on a very stylistic look and feel. By pressing any of the four refresh buttons in the lower portion of the window, the background is changed to a different bitmap (there are six in all).

Additional thanks goes to Paul Nettle for his winDIB routines.

A Bit About Anti-Aliasing and Alpha-Blending

One of the trickiest parts of masking images on top of images is the rough edges, or pixelation, of the meeting places of these images when they are not straight edges. The solution to these rough edges is to blend the edges in a technique called anti-aliasing. In this demo, anti-aliasing is done using an alpha-blending technique, where the transparency of the foreground bitmap pixel determines the strength of color at any particular position on the display.

The formula for blending source and background pixels is:

displayColor = sourceColor � sourceAlpha / 255 + backgroundColor � (255 � sourceAlpha) / 255

where the alpha value range is 0 (transparent) to 255 (opaque). Therefore, any part of the button's bitmap that has an alpha value of 0 will not be seen, and areas with values greater than zero will be blended with the background at varying strengths up to 255 where the button's bitmap will be fully opaque.

// alphaBlend routine

static inline unsigned int alphaBlend(const unsigned 
                      int bg, const unsigned int src)
{
    unsigned int    a = src >> 24;    // sourceColor alpha


    // If source pixel is transparent, just return the background

    if (0 == a) return bg;

    // alpha-blend the src and bg colors

    unsigned int rb = (((src & 0x00ff00ff) * a) + 
          ((bg & 0x00ff00ff) * (0xff - a))) & 0xff00ff00;
    unsigned int    g  = (((src & 0x0000ff00) * a) + 
          ((bg & 0x0000ff00) * (0xff - a))) & 0x00ff0000;

    return (src & 0xff000000) | ((rb | g) >> 8);
}

Creating The Bitmaps

As explained, in order to blend the button bitmap with the background, the button bitmap must have an alpha value assigned to each pixel. This means that these bitmaps must be 32-bit-per-pixel (32bpp) images where the byte order is Alpha, Red, Green, Blue (ARGB).

One way to create this type of image is to use Adobe Photoshop. Create a new image with the color mode CMYK, making sure that the background color is set to black. Photoshop can automatically anti-alias edges for you against the black background. Save the file as a .RAW type, which only saves the actual bytes of the image and no header information. Unfortunately, the order of the .RAW image will be ABGR, so there is a bit reordering that must be done before blending, but this is no big deal.

Import the bitmaps into your project as a new resource type, "RAW". The bitmaps can now be loaded as resources for use on the buttons.

// This routine loads raw bitmap data from a resource.

// The width and height must be defined as there is no bitmap header

//

// Note that the resource type is "RAW" here, but can be changed to 

// any name, or passed as a parameter if desired

BOOL CHoverButtonEx::LoadRaw(UINT rawid, long nWidth, long nHeight)
{
    //If Bitmaps are being loaded and the BS_OWNERDRAW is not set

    // then reset style to OwnerDraw.

    UINT style = GetButtonStyle();
    if (!(style & BS_OWNERDRAW))
    {
        style |= BS_OWNERDRAW;
        SetButtonStyle(style);
    }

    m_pRaw = NULL;
    CString resName;
    resName.Format("#%d", rawid);
    HGLOBAL hRaw = LoadResource(AfxGetResourceHandle(), 
        FindResource(AfxGetResourceHandle(), resName, "RAW"));
    if (!hRaw)
        return FALSE;

    m_pRaw = (unsigned int*)LockResource(hRaw);

    if (!m_pRaw)
        return FALSE;

    m_nRawWidth = nWidth;
    m_nRawHeight = nHeight;

    // The bitmap should contain four images:

    // normal, selected, hover, and disabled.

    // The images must be the same size within

    // the bitmap, but can be laid out

    // horizontally or vertically.

    if (!m_bHorizontal)
    {
        m_ButtonSize.cy=nHeight/4;
        m_ButtonSize.cx=nWidth;
    }
    else
    {
        m_ButtonSize.cy=nHeight;
        m_ButtonSize.cx=nWidth/4;
    }

    SetWindowPos( NULL, 0,0, m_ButtonSize.cx, 
        m_ButtonSize.cy,SWP_NOMOVE | SWP_NOOWNERZORDER );

    return TRUE;
}

Using the code

Adding transparent bitmapped buttons is very easy to implement.

  1. Create any number of owner-draw buttons on your dialog or view.
  2. Include the HoverButton header in your dialog or view header where the buttons are declared.
    #include "HoverButton.h"
    
    .
    .
  3. Change the button types to CHoverButtonEx.
        CHoverButtonEx m_Btn1;
        CHoverButtonEx m_Btn2;
        CHoverButtonEx m_Btn3;
  4. Create a region for the buttons, and assign parameters.
        // Create round buttons
    
        HRGN r = CreateEllipticRgn(0, 0, 48, 48);
    
        m_Btn1.SetHorizontal(TRUE);
        m_Btn1.SetRegion(r);
        m_Btn1.LoadRaw(IDR_RED, 192, 48);
        m_Btn1.SetToolTipText("Press Me!");
    
        m_Btn2.SetHorizontal(TRUE);
        m_Btn2.SetRegion(r);
        m_Btn2.LoadRaw(IDR_PURPLE, 192, 48);
        m_Btn2.SetToolTipText("Press Me!");
    
        m_Btn3.SetHorizontal(TRUE);
        m_Btn3.SetRegion(r);
        m_Btn3.LoadRaw(IDR_PURPLE, 192, 48);
        m_Btn3.SetToolTipText("Press Me!");
    
        DeleteObject(r);
  5. If the background changes, simply call RefreshBkgrnd.
        m_Btn1.RefreshBkgrnd();
        m_Btn2.RefreshBkgrnd();
        m_Btn3.RefreshBkgrnd();

That's it!

Points of Interest

One of the interesting routines here is how to determine what the background looks like. I decided to read the background before the button is first displayed, and save that image until the button is refreshed.

// If this is the first time drawing the button, or the background

// has been refreshed, we need to "read" the background and save

// it for transparency mixing (aka alpha blending).

if (m_pRaw && m_nRawWidth && m_nRawHeight && !m_bLoadBkgrnd)
{
    unsigned int bkPix;
    COLORREF c;

    int bkWidth;
    int bkHeight;

    // Get the size of one image

    if (!m_bHorizontal)
    {
        bkWidth = m_nRawWidth;
        bkHeight = m_nRawHeight/4;
    }
    else
    {
        bkWidth = m_nRawWidth/4;
        bkHeight = m_nRawHeight;
    }

    if (m_pBkGrnd)
        delete m_pBkGrnd;

    // Create array to hold background pixels

    m_pBkGrnd = new unsigned int;

    if (!m_pBkGrnd)
        return;

    unsigned int* pBkGrnd = m_pBkGrnd;

    for (int iY = 0; iY < bkHeight; iY++)
    {
        for (int iX = 0; iX < bkWidth; iX++, pBkGrnd++)
        {
            // Get the background pixel

            c = mydc->GetPixel(iX, iY);
            bkPix = (unsigned int)c;
            bkPix |= 0xff000000;        // Set pixel opaque

            // Set correct order of RGB

            bkPix = (bkPix&0xff00ff00) | ((bkPix>>16)&0xff) 
                               | ((bkPix<<16)&0xff0000);

            // Save pixel in array

            *pBkGrnd = bkPix;
        }
    }

    m_bLoadBkgrnd = TRUE;
}

This method provides an accurate picture of the background, especially if the background has been stretched or tiled from the original image. Another method of determining the background might be to pass the background bitmap to the button class, and calculate the offsets, or simply pass a color reference if the background is not a bitmap. Any of these other methods might prove more efficient in selected cases.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Bob Carboni


Member
Software architect and developer with over 20 years of experience, specializing in GUI designs and intranet systems in MFC/C++ and ASP.Net using C#.
Occupation: Web Developer
Location: United States United States

Other popular Button Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 35 (Total in Forum: 35) (Refresh)FirstPrevNext
QuestionHow to load raw image at runtime PinmemberMickeyJC3:57 17 Jul '08  
GeneralTransparent Button with Region and Anti-Aliased Edges PinmemberCGroff2:05 8 Jul '08  
GeneralThanks a lot! PinmemberAlex Cohn5:35 23 Oct '07  
GeneralWhy not use straight png files [modified] PinmemberMark Hagers6:28 30 Aug '07  
Generallittle bug Pinmembergrandmasta10:59 12 Jul '07  
QuestionHow to create RAW ffrom PNG PinmemberSir.Costy23:06 19 Jun '07  
AnswerRe: How to create RAW ffrom PNG PinmemberBob Carboni5:12 20 Jun '07  
QuestionCan I use Bitmaps and not raw images? PinmemberSir.Costy23:46 30 May '07  
GeneralHow can I change the image? Pinmember15:37 7 Mar '07  
GeneralRe: How can I change the image? PinmemberBob Carboni13:52 8 Mar '07  
GeneralWould you Please send me the bmp before raw? Pinmemberhongming666223:59 1 Feb '07  
GeneralRe: Would you Please send me the bmp before raw? PinmemberBob Carboni6:04 2 Feb '07  
GeneralTransparency dosen't work with buttons on toolbars :( PinmemberSir.Costy6:27 15 Jan '07  
GeneralRe: Transparency dosen't work with buttons on toolbars :( PinmemberBob Carboni14:42 30 Jan '07  
QuestionAnti - aliased background ? PinmemberVirtual Reality9:47 15 Dec '06  
AnswerRe: Anti - aliased background ? PinmemberBob Carboni14:02 8 Mar '07  
GeneralHow can I do that with VB.net? Pinmemberalexmbra7:05 17 May '06  
GeneralRe: How can I do that with VB.net? PinmemberBob Carboni10:15 17 May '06  
GeneralCMYK Black is different from RGB Black Pinmemberotterrrr9:48 11 Dec '05  
GeneralNice but question on button response PinmemberCosmoNova22:00 4 Sep '05  
GeneralDoes not work with window alway on top Pinmemberdaniel_zy4:53 18 May '05  
GeneralHow to use it in WTL ? Pinmembericer.L1:07 27 Feb '05  
GeneralRe: How to use it in WTL ? PinmemberBob Carboni4:37 28 Feb '05  
GeneralHow to create the .Raw files Pinmemberdurbin12:52 21 Dec '04  
GeneralRe: How to create the .Raw files PinmemberBob Carboni5:56 22 Dec '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Aug 2004
Editor: Smitha Vijayan
Copyright 2004 by Bob Carboni
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project