When repaint my pictureboxes(from listUC) on a panel, i want to draw a ellipse and a string on each pictureBox. But nothing was drawn on the pictureBox.
I want to draw the string wich is stored in the uc.Name;
foreach (UseCase uc in listUC)
{
ucNamePaint = uc.Name;
//Create UseCaseBox
PictureBox useCaseBox = new PictureBox();
useCaseBox.Name = uc.Index.ToString();
Graphics g = useCaseBox.CreateGraphics();
useCaseBox.Paint += new PaintEventHandler(OnPaint_picturebox);
}
Onpaint method:
private void OnPaint_picturebox(object sender, EventArgs e)
{
var pb = sender as PictureBox;
if (null != pb)
{
pb.BackColor = Color.Yellow;
Graphics g = pb.CreateGraphics();
Font drawFont = new Font("Arial", 10);
int stringWidth = (int)g.MeasureString(ucNamePaint, drawFont).Width;
int stringHeight = (int)g.MeasureString(ucNamePaint, drawFont).Height;
if (selectedUC.Count() != 0)
{
Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
using (Pen pen = new Pen(Color.Black, 2))
{
g.DrawEllipse(pen, ee);
}
}
else
{
Rectangle ee = new Rectangle(0, 0, stringWidth + 10, stringHeight + 10);
using (Pen pen = new Pen(Color.Gray, 2))
{
g.DrawEllipse(pen, ee);
}
}
StringFormat drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Center;
float emSize = pb.Height;
g.DrawString(ucNamePaint, new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular),
new SolidBrush(Color.Black), 7, 5);
}
}
This code paints the picturebox yellow but nothing else is painted. Please explain me how to fix this!
If I would be you, I would create a Bitmap for each PictureBox. Assign them to the PictureBox like this pictureBox.Image = bitmapImg;
Create the Graphics from the Bitmap using Graphics g = Graphics.FromImage(bitmapImg);
I suggest clearing the Graphics each time you draw them. Use: g.Clear(Color.Yellow);
Now you can do all your magic you did in your code above.
Edit: Forgot to mention you have to use the DrawImage method to write the graphics to a bitmap. Use g.DrawImage(bitmapImg, ...);
The signature of the OnPaint
method should really be:
private void OnPaint_picturebox(object sender, PaintEventArgs e)
then change this
Graphics g = pb.CreateGraphics();
to
Graphics g = e.Graphics;
Also it's definitely not a good idea to set paint related properties inside the paint handler. So, instead of
pb.BackColor = Color.Yellow;
use
g.Clear(Color.Yellow);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.