I want to draw a text over a PictureBox in a foreach loop. This is the code that is responsible for rendering(GG is a PictureBox that is currently in the loop)

if (GG != null)
      {
            ((PictureBox)GG).Image = (Image)obj;
            using (Graphics g = ((PictureBox)GG).CreateGraphics()) {
            g.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font, 
            new SolidBrush(Color.Gold), new Point(16, 18));
      }

}

But sadly, the text is not rendered. If I comment out the

//((PictureBox)GG).Image = (Image)obj;

line, it does work! I have no idea how to get it to work.

I wanted to use the TextRenderer, but I don't know how to get an IDeviceContext of a control(and all examples I see on the internet use PaintEventArgs.Graphics in Paint event).

Also, if this is relevant, the GG PictureBox is a child of another picturebox, and has a transparent background.

I tried to refresh the box after invalidating, the working code:

if (GG != null)
      {
            ((PictureBox)GG).Image = (Image)obj;
            ((PictureBox)GG).Invalidate();
            ((PictureBox)GG).Refresh();
            using (Graphics g = ((PictureBox)GG).CreateGraphics()) {
            g.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font, 
            new SolidBrush(Color.Gold), new Point(16, 18));
      }

}
有帮助吗?

解决方案

You modified the image content but the PictureBox is completely unaware of that. You didn't reassign its Image property. You will need to tell it that it needs to redraw the image as displayed on the screen. Add this line of code:

    GG.Invalidate();

其他提示

Just draw on a Bitmap and show it in the PictureBox:

// A new bitmap with the same size as the PictureBox
var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);

//Get the graphics objectm which we can use to draw
var graphics = Graphics.FromImage(bitmap);

//Draw stuff
graphics.DrawString(i["amount"].ToString(), kryptonRichTextBox1.Font, 
        new SolidBrush(Color.Gold), new Point(16, 18));

//Show the bitmap with graphics image in the PictureBox
pictureBox.Image = bitmap;
        Image digidashboard = new Bitmap(Properties.Resources.digidashboard);
        //using (Graphics g = ((PictureBox)pictureBoxDashboard).CreateGraphics())
        //{
        //    g.DrawString("80.00", this.Font, new SolidBrush(Color.Red), 3, 6);
        //    pictureBoxUnlock.Image = digidashboard;
        //    pictureBoxDashboard.Invalidate();
        //}
        Graphics g = Graphics.FromImage(digidashboard);
        g.DrawString("80.00", this.Font, new SolidBrush(Color.Red), 3, 6);
        pictureBoxDashboard.Image = digidashboard;

According to StevenHouben's answer, I paste my C# version. It works fine. Thanks @StevenHouben.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top