Reputation: 33
Found examples of using transparency with a background image, but this option does not suit me. Since it is assumed that the background will change upon certain actions.
Upvotes: 0
Views: 391
Reputation: 6607
Not sure what you are doing as details are light, but hope this is helpful. We use icons (.ico) files with transparency as follows. These just change the background to a single colour. If you need more complex behaviour, then this may not be suitable.
Add some icons (with transparent backgrounds) to your project. Set the Build Action
as Embedded Resource
. In the example below we use an icon called ico1.ico
.
Define a structure to hold your icons. Depending on the number of background colours you require, there would be an instance for each icon/colour combination you need. If the number is very large or unknown at design-time then you'll need to create the icons on-the-fly.
public struct CacheGraphics
{
public Bitmap ico1White, ico1Blue;
}
public static CacheGraphics cacheGraphics;`
Cache the icons:
cacheGraphics.ico1White = new Bitmap(GetIconImage("ico1", Color.White));
cacheGraphics.ico1Blue = new Bitmap(GetIconImage("ico1", Color.Blue));`
Write a helper function which modifies the background colour:
private static Bitmap GetIconImage(string szIcon, Color clrBackground)
{
// Convert an embedded icon into an image
// Load icon
string szImage = ("YOUR-PROJECT.Resources.Icons." + szIcon + ".ico");
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream file = _assembly.GetManifestResourceStream(szImage);
Icon icoTmp = new Icon(file);
// Create new image
Bitmap bmpNewIcon = new Bitmap(icoTmp.Width, icoTmp.Height, PixelFormat.Format32bppRgb);
// Create a graphics context and set the background colour
Graphics g = Graphics.FromImage(bmpNewIcon);
g.Clear(clrBackground);
// Draw current icon onto the bitmap
g.DrawIcon(icoTmp, 0, 0);
// Clean up...
g.Dispose();
// Return the new image
return bmpNewIcon;
}
Define a simple alias for each icon:
// Alias which goes at the top of any file using icons: using icons = YOUR-PROJECT.CCommon.AppIcons;
public enum AppIcons
{
ICO1_WHITE,
ICO1_BLUE
}
Write a helper function to return the cached icon on request:
public static Image GetCachedIcon(AppIcons eIcon)
{
// Return a cached icon image. These icons are cached at application startup.
Image imgIcon = null;
switch (eIcon)
{
// System Settings > Advanced
case AppIcons.ICO1_WHITE:
imgIcon = (Image)cacheGraphics.ico1White; break;
case AppIcons.ICO1_BLUE:
imgIcon = (Image)cacheGraphics.ico1Blue; break;
}
return imgIcon;
}
Use icon when required:
picturebox1.Image = CCommon.GetCachedIcon(icons.ICO1_WHITE);
picturebox2.Image = CCommon.GetCachedIcon(icons.ICO1_BLUE);
Upvotes: 1