Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Painting a command button in two colors

I have what looks like a very simple task: painting the
background of a command button half red, half green. The
code I've come up with works fine, but somehow I don't
think this is the best  or most efficient way to go:

int H = btnTarget.Size.Height;
int W = btnTarget.Size.Width;
Bitmap bmp = new Bitmap(W,H);
fillBitmap(bmp,0,0,W/2,H,Color.Red );
fillBitmap(bmp,W/2,0,W/2,H,Color.LawnGreen );
btnTarget.BackgroundImage = bmp;

Where fillBitmap function is as follows:

private void fillBitmap(Bitmap pBmp, int X, int Y, int W, int H, Color pColor)
{
  int i,j;
  for(i=X;i<X+W;i++)
      for(j=Y;j<Y+H;j++)
          pBmp.SetPixel(i,j,pColor);        
}


If I needed to paint the whole button over (and not just
the background), I'd simply use the Graphics.FillRectangle,
but that would obliterate the button's text.

Any advice would be appreciated.

Mike
Monday, October 20, 2003

I don't see any other way to do this.  The only potential efficiency improvement I can see is in the matter of when and where you create the bitmap.  Presumably you're inheriting from Button, setting bmp as a variable in the general class declarations section, and creating and coloring the bitmap in the New event rather than recreating it with every OnPaint.  Or you could save the bitmap with your app, but of course that disencapsulates it from the button.  (deencapsulates?  unencapsulates?)

So...out of curiosity, why do you want to do this anyway?  The colors will probably be indistinguishable to colorblind people, and won't be seen by blind people, and may well make the button harder to read for everyone else.

Kyralessa
Monday, October 27, 2003

Thanks for the reply. I was almost convinced there's no
other way around this. Building bmp's doesn't take any noticeable time, so I don't have a problem doing that
each time I need as opposed to pre-creating them
for later use.

To address your curiosity, this is a desktop app for internal use in the company, and colors are goind to be used  to notify the user when nes items arrive in their inbox. There are two kinds of items, hence two colors, and for a rare
case when items of both types arrive, the mixed color will be used.

Thanks again.

Mike
Thursday, October 30, 2003

*  Recent Topics

*  Fog Creek Home