Graphics.DrawString 不起作用



我想在foreach循环中的图片框上绘制文本。这是负责渲染的代码(GG是当前在循环中的picturebox)

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));
      }
}

但可悲的是,文本没有呈现。如果我评论

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

行,它确实有效!我不知道如何使它起作用。

我想使用Textrenderer,但我不知道如何获得控件的iDevicecontext(以及我在互联网上看到的所有示例都使用PaintEventargs.graphicts.graphicts。

另外,如果这是相关的,则GG Picturebox是另一个picturebox的孩子,并且具有透明的背景。

我试图在无效后刷新盒子,即工作代码:

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));
      }
}

您修改了图像内容,但图片框完全没有意识到。您没有重新分配其图像属性。您需要告诉它,它需要重新绘制屏幕上显示的图像。添加此代码线:

    GG.Invalidate();

只是在Bitmap上绘制并在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;

根据史蒂文胡本的回答,我粘贴了我的C#版本。它可以正常工作。谢谢@stevenhouben。

最新更新