A solution for advanced control having transparent background

Add-in Express™ Support Service
That's what is more important than anything else

A solution for advanced control having transparent background
Solution for transparent picture box to be displayed on a command bar 
C T




Posts: 14
Joined: 2009-03-13
Hi all,

I've came across this problem the previous days. I had a logo image (in a .Net PictureBox) to display on the command bar but I couldn't make the background of the hosting control to be transparent and therefore the logo was not looking good. I've seen also that currently there was no acceptable solution for this problem on the forum.

I'm posting this solution in hope that it will help someone else.

One has to inherit from PictureBox, override OnHandleCreated and set the region of the parent control acordingly.

[Browsable(true)]
public Color TransparencyKey
{
get;
set;
}


protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);

if (Parent != null)
{
var region = ImageContourRegion();

// this translation worked for me because the image was centered
// in the picture box and the size of the picture box was set to
// the image size

region.Translate(0, 3);

this.Parent.Region = region;
}
}


Now you are using this .Net custom control to fill the adx advance control on the command bar.

Creating the visible region from the attached image means ignoring the transparency color, which is set by the user in VS designer by using the TransparencyKey property, while creating a region from visible pixels.

private Region ImageContourRegion()
{
if (this.TransparencyKey == Color.Empty)
{
return new Region(new Rectangle(new Point(), this.Image.Size));
}

Region region = new Region(new Rectangle(0,0,0,0));

using (var bitmap = new Bitmap(this.Image))
{
var transparency = this.TransparencyKey.ToArgb();

for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
var color = bitmap.GetPixel(x, y);

if (color.ToArgb() != transparency)
{
region.Union(new Rectangle(x, y, 1, 1));
}
}
}
}

return region;
}


If you do this you will have a transparent image in on the command bar.

This might also be applied to different .Net controls if the result of the control's OnPaint creates the displayable region.

Have fun,
TC
Posted 16 Jun, 2009 04:43:18 Top
Andrei Smolin


Add-in Express team


Posts: 18830
Joined: 2006-05-11
Thank you!


Andrei Smolin
Add-in Express Team Leader
Posted 16 Jun, 2009 06:59:24 Top