在Picturebox上添加一个标签 [英] Add a Label over Picturebox
本文介绍了在Picturebox上添加一个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在试图在我的picturebox上写一些文字,所以我认为最简单和最好的做法是在它上面绘制标签。这是我做的:
I am trying to write some text over my picturebox so I thought the easiest and best thing to do is draw label over it. This is what I did:
PB = new PictureBox();
PB.Image = Properties.Resources.Image;
PB.BackColor = Color.Transparent;
PB.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
PB.Size = new System.Drawing.Size(120, 30);
PB.Location = new System.Drawing.Point(100, 100);
lblPB.Parent = PB;
lblPB.BackColor = Color.Transparent;
lblPB.Text = "Text";
Controls.AddRange(new System.Windows.Forms.Control[] { this.PB });
我没有使用PictureBox的空白页面。我做错了什么?
I get blank page with no PictureBoxes. What am I doing wrong?
推荐答案
尽管所有这些答案都有效,但您应该考虑选择更清晰的解决方案。您可改为使用图片框的 Paint
事件:
$ b
While all these answers work, you should consider opting for a cleaner solution. You can instead use the picturebox's Paint
event:
PB = new PictureBox();
PB.Paint += new PaintEventHandler((sender, e) =>
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
e.Graphics.DrawString("Text", Font, Brushes.Black, 0, 0);
});
//... rest of your code
编辑以文本为中心:
Edit To draw the text centered:
PB.Paint += new PaintEventHandler((sender, e) =>
{
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
string text = "Text";
SizeF textSize = e.Graphics.MeasureString(text, Font);
PointF locationToDraw = new PointF();
locationToDraw.X = (PB.Width / 2) - (textSize.Width / 2);
locationToDraw.Y = (PB.Height / 2) - (textSize.Height / 2);
e.Graphics.DrawString(text, Font, Brushes.Black, locationToDraw);
});
这篇关于在Picturebox上添加一个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文