I am trying to draw a circle using Windows Form at runtime inside a label control. I am trying to display green or red circle and display the text('L1开发者_Python百科' or 'L2') on top of it. Could you please help.
First you need to SetStyle in the Constructor so you can control the paint
this.SetStyle(
ControlStyles.UserPaint
| ControlStyles.AllPaintingInWmPaint
| ControlStyles.SupportsTransparentBackColor
, true );
Then you are responsible for painting the entire label including the background and the text. Override OnPaint
protected override void OnPaint( PaintEventArgs e ) {
Graphics g = e.Graphics;
Brush b = new SolidBrush( this.ForeColor );
SizeF sf = g.MeasureString( this.Text, this.Font );
Padding p = Padding.Add( this.Padding, this.Margin );
// do not forget to include the offset for you circle and text in the x, y position
float x = p.Left;
float y = p.Top;
g.DrawString( this.Text, this.Font, b, x, y );
}
After you have draw the label text, then use g.DrawEllipse to draw the circle you want and where you want. Then use g.DrawString to position the text above it.
Keep in mind that if you must provide everything bit of the paint that you set properties for so this is only to be used for the labels that conform to the standard you are going to set
To do this programmatically you can use the Label's CreateGraphics
method to get the Graphics
. You can then use the DrawElipse
and the DrawString
methods to create the image you want.
If you have a resource Image, you can set the Image property on the Label, and then set the Text Alignment and the Image Alignment properties to get it to fall where you want.
Totally agree with Nick. Have 4 images with various combination and show it dynamically.
Hope this helps.
Thanks, Raja
精彩评论