Ant*_*tin 2 c# forms label picturebox
我试图在我的图片框上写一些文字,所以我认为最简单和最好的事情是在它上面绘制标签.这就是我做的:
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 });
Run Code Online (Sandbox Code Playgroud)
我得到没有PictureBoxes的空白页面.我究竟做错了什么?
pre*_*sto 16
虽然所有这些答案都有效,但您应该考虑选择更清洁的解决方案.您可以改为使用图片框的Paint活动:
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
Run Code Online (Sandbox Code Playgroud)
编辑以中心绘制文本:
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);
});
Run Code Online (Sandbox Code Playgroud)
代替
lblPB.Parent = PB;
Run Code Online (Sandbox Code Playgroud)
做
PB.Controls.Add(lblPB);
Run Code Online (Sandbox Code Playgroud)