我有一个包含图片框和标签的用户控件。控件根据不同的事件(例如 onMouseEnter、OnMouseLeave)在 PictureBox 中加载三个不同的图像。由于图像可以有不同的大小,我需要调整图片框和控件本身的大小。下面提供了控件的 OnPaint 事件,但这不起作用。
protected override void OnPaint(PaintEventArgs pe)
{
if (pictureBox.Image != null)
{
this.Width = this.pictureBox.Image.Size.Width;
this.Height = this.pictureBox.Image.Size.Height;
CutRoundedRectangle2(pictureBox, cornerRadius);
}
else
{
Bitmap DrawArea = new Bitmap(pictureBox.Size.Width, pictureBox.Size.Height);
Graphics g = Graphics.FromImage(DrawArea);
Pen mypen = new Pen(Color.Black);
pictureBox.Image = DrawArea;
System.Drawing.Pen pen = new Pen(new SolidBrush(this.ForeColor));
g.DrawRectangle(pen, 0, 0, this.Width-1, this.Height-1);
g.Dispose();
}
this.labelText.ocation = new Point((this.pictureBox.Width - this.labelText.Width) / 2,
(this.pictureBox.Height - this.labelText.Height) / 2);
base.OnPaint(pe);
}
pictureBox SizeMode 在控件的构造函数中设置:
this.pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;