简体   繁体   中英

c# Resize parent control when a child pictureBox changes the Image

I have a UserControl that contains a PictureBox and a Label. The Control loads three different images in PictureBox on different events (fore example onMouseEnter, OnMouseLeave). As the images can have different sizes, I neet to resize the pictureBox and the control itself. Below is provided the control's OnPaint event but this does not work.

    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);
    }

The pictureBox SizeMode is set in control's constuctor:

this.pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;

It was long time ago when I worked with WinForms last time, but ...
My first thought is: have you tried set value of parent control's AutoSize property to 'true' and AutoSizeMode to GrowAndShrink and call parent control's Refresh() method when new image is loaded to picture box?

@Alexey, the pictureBox resize event helped!

    private void pictureBox_Resize(object sender, EventArgs e)
    {
        this.Width = this.pictureBox.Image.Size.Width;
        this.Height = this.pictureBox.Image.Size.Height;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM