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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 01:47:00

问题


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;

回答1:


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?




回答2:


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


来源:https://stackoverflow.com/questions/11527680/c-sharp-resize-parent-control-when-a-child-picturebox-changes-the-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!