WinForms: Make a collapse/expand image button
This is a followup to this SO question: How do I make a collapsible UI region on the form?
I'm making a winforms app with a region (panel) that is expandable or collapsible.
I used the expand/collapse bitmaps from the VS2008 Image library, for the buttons. I put those two into an ImageList.
I wanted the button to have no border, so I set FlatStyle = Flat, FlatAppearance.BorderSize = 0.
On the click event for the button, I have
private void button1_Click(object sender, EventArgs e)
{
if (splitContainer1.Panel1Collapsed == true)
{
splitContainer1.Panel1Collapsed = false;
button1.ImageIndex = 0;
this.toolTip1.SetToolTip(this.button1, "Collapse");
}
else
{
splitContainer1.Panel1Collapsed = true;
button1.ImageIndex = 1;
this.toolTip1.SetToolTip(this.button1, "Expand");
}
}
But the transparency in the bitmap is not respected. My understanding was that the color used in the top-left (or is it bottom-left?) corner of the bitmap will be treated as transparent, so when the bitmap is displayed, any pixels with that same color value will be transparent. But I don't get those results. Instead I get the transparent color to show up as its true color.
I found a way t开发者_开发百科o avoid this by providing an OnPaint method for the button, and manually drawing the bmp after calling MakeTransparent() on it, like this:
private void button1_Paint(object sender, PaintEventArgs e)
{
// This draws the image on the button, and makes the bmp
// background color as transparent. Why this isn't done
// automatically, I don't know.
Bitmap bmp = (Bitmap) imageList1.Images[button1.ImageIndex];
bmp.MakeTransparent();
int x = (button1.Width - bmp.Width) / 2;
int y = (button1.Height - bmp.Height) / 2;
e.Graphics.DrawImage(bmp, x, y);
}
But isn't there a simpler way?
You need to set the TransparentColor property on the ImageList.
精彩评论