[英]Graphics.DrawString doesn't work
我想在foreach循環中的PictureBox上繪制文本。 這是負責渲染的代碼(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(我在互聯網上看到的所有示例都使用Paint事件中的PaintEventArgs.Graphics)。
此外,如果這是相關的,GG 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));
}
}
您修改了圖像內容,但PictureBox完全沒有意識到這一點。 您沒有重新分配其Image屬性。 您需要告訴它需要重繪屏幕上顯示的圖像。 添加以下代碼行:
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;
根據StevenHouben的回答,我粘貼了我的C#版本。 它工作正常。 謝謝@StevenHouben。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.