Wednesday, June 07, 2006

Questions about how to make the Label control in CF transparent come up on the newsgroups or forums all the time. People want to have a transparent label on a top of an image. The answer to that is that transparency in the controls is not supported on the OS level. But what is the Label control? It is just a text drawn on a graphic surface. So this is what I've been doing -  drawing a text string on a top of an image. But not loose the design time goodness that you get with the Label, I was using the Label's properties (Text, Font, Location, Size etc..) to draw the required string in the location instead of the Label:

private void DrawLabel(Label label, Graphics grx)

{

      if (label.TextAlign == ContentAlignment.TopLeft)

      {

           gxOff.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), label.Bounds);

      }

      else if (label.TextAlign == ContentAlignment.TopCenter)

      {

           SizeF size = grx.MeasureString(label.Text, label.Font);

           int left = this.Width / 2 - (int)size.Width / 2;

           Rectangle rect = new Rectangle(left, label.Top,  (int)size.Width, (int)label.Height);

           gxOff.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);

      }

      else if (label.TextAlign == ContentAlignment.TopRight)

      {

           SizeF size = grx.MeasureString(label.Text, label.Font);

           int left = label.Width - (int)size.Width + label.Left;

           Rectangle rect = new Rectangle(left, label.Top, (int)size.Width, (int)size.Height);

           gxOff.DrawString(label.Text, label.Font, new SolidBrush(label.ForeColor), rect);

      }

 }

In order to use this method you can assign an image to the PictureBox, drop a Label control on a top of a PictureBox, set Label 's Visible proprerty to false and call the DrawLabel method in the Paint event of the PictureBox.

6/7/2006 4:51:53 PM (GMT Daylight Time, UTC+01:00)  #     |