How to Programmatically Create a Silverlight Brush

How to Programmatically Create a Silverlight Brush

To create a Silverlight for Windows Embedded brush programmatically, you need to understand brush opacity so that you don’t inadvertently paint with a transparent brush.

In the Mastermind code sample, created by using Silverlight for Windows Embedded, I chose to programmatically create the brushes that I would use to paint the black and white feedback pegs that display how accurate the player’s guess is. I chose not to create these brushes using Expression Blend because I don’t need brushes that have a gradient or other special visual effects.

Mastermind Game

One of the issues I encountered when I first created a brush was that I couldn’t see anything happen on the screen when I used the brush to paint. Consider the following code, located found in the MainPage::InitializeMastermind() function in the MainPage.cpp file of the Mastermind code sample, that I used to create a brush. In this code sample I have removed the error handling code and made other minor changes for clarity.

IXRApplicationPtr pApplication = NULL;
IXRSolidColorBrushPtr pWhiteBrush = NULL;
GetXRApplicationInstance( &pApplication );
COLORREF WhiteColor = RGBA(255, 255, 255, 255); // set the 'a' argument = 255 for full opacity -- we don't want invisible brushes
pApplication->CreateObject( &pWhiteBrush );

When I first created the white brush, I used the RGB macro to create the COLORREF value. But when I used the brush, nothing seemed to happen. The problem is that COLORREF has an opacity component, and if you use the RGB macro to generate a COLORREF, the opacity is set to 0 by default, which means it is transparent. I was painting with a transparent brush!

The solution to the transparency issue is to use the RGBA macro, with which you can set the alpha value. The alpha value ranges from 0 (fully transparent) to 255 (fully opaque). When I used the RGBA macro and specified the alpha value that corresponds to fully opaque, I could see on the screen the effects of painting with the brush.

See Also

Leave a Comment
  • Please add 7 and 3 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
  • Carsten Siemens edited Revision 6. Comment: Added tags: en-US, has See Also, has Image, has comment

Page 1 of 1 (1 items)
Wikis - Comment List
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
  • Carsten Siemens edited Revision 6. Comment: Added tags: en-US, has See Also, has Image, has comment

  • Great job on embedding the code!

Page 1 of 1 (2 items)