2

我有一个包含图片框和标签的用户控件。控件根据不同的事件(例如 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;
4

2 回答 2

1

上次我使用 WinForms 是很久以前的事了,但是……
我的第一个想法是:您是否尝试过将父控件AutoSize属性的值设置为 'true' 并在新图像加载到图片框时AutoSizeMode调用GrowAndShrink父控件的方法Refresh()?

于 2012-07-17T17:33:20.700 回答
0

@Alexey,pictureBox 调整大小事件有帮助!

    private void pictureBox_Resize(object sender, EventArgs e)
    {
        this.Width = this.pictureBox.Image.Size.Width;
        this.Height = this.pictureBox.Image.Size.Height;
    }
于 2012-07-18T12:22:29.547 回答