Größe der Picturebox zur Laufzeit ändern

sailer86

Grünschnabel
Hi,

kann mir jemand sagen, wie ich die größe einer Picturebox zur Laufzeit ändern kann.

Mein Code ist bis jetzt folgender:
Code:
 private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Geraet));
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.name = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(82, 41);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mouseDown);
            this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mouseMove);
            this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mouseUp);
            // 
            // name
            // 
            this.name.AutoSize = true;
            this.name.Location = new System.Drawing.Point(21, 13);
            this.name.Name = "name";
            this.name.Size = new System.Drawing.Size(41, 13);
            this.name.TabIndex = 1;
            this.name.Text = "[Name]";
            this.name.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mouseDown);
            this.name.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mouseMove);
            this.name.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mouseUp);
            // 
            // Geraet
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.name);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Geraet";
            this.Size = new System.Drawing.Size(85, 44);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mouseDown);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mouseMove);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mouseUp);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        private void mouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                beginMovingPointMouse = new Point(e.X, e.Y);
                beginMovingPointControl = this.Location;
            }
        }
    
        private void mouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                int deltaX = e.X - beginMovingPointMouse.X;
                int deltaY = e.Y - beginMovingPointMouse.Y;

                this.Left += deltaX;
                this.Top += deltaY;
            }            
        }
    
        private void mouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
            beginMovingPointMouse = Point.Empty;
            beginMovingPointControl = Point.Empty;
        }

Zudem will ich den Pfad des Images aus einer xml auslesen. Das auslesen funktioniert auch wunderbar. Aber wie schreibe ich denn dann in der picturebox hin das der ausgelesene Pfad genommen werden soll? Ich habe es so probiert aber das funktioniert nicht.
Code:
    this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject(pfad)));


Kann mir jemand helfen?

Lieben Dank
sailer
 
Hallo,

um die Größe einer PictureBox zu ändern muss du nur die Height und Width Properties anpassen. Wenn du willst, dass das Bild mitskaliert wird, dann hast du 2 Möglichkeiten. Du setzt das SizeMode auf Zoom oder du Zeichnest das Bild (Image) neu und weist es dem PictureBox zu.
Zu deinem 2ten Problem, wenn du den (Datei-)Pfad von dem Bild hast, dann brauchst du nur folgendes zu tun:
Code:
PictureBox picture = new PictureBox();
picture.Image = Image.FromFile(pathToImage);

Gruß Konstantin
 
Hi,

vielen Dank für deine Anwort. Ich habe es probiert folgendermaßen zu machen. Aber das funktioniert nicht.

Registrieren des Events:

Code:
 this.pictureBox1.SizeChanged += new System.EventHandler(this.pictureBox1_SizeChanged);

und das Event dann:
Code:
 private void pictureBox1_SizeChanged(object sender, EventArgs e)
        {
            Control control = (Control)sender;

            control.Size = new Size(control.Size.Width, control.Size.Width);
        }

Aber es passiert nichts. Außerdem will ich das ein Pfeil (<-> oder anderer) erscheint, wenn ich die PictureBox verkleinern/vergrößern will. Aber nichst passiert.:confused:

Weis jemand was ich falsch mache?

LG
sailer
 
Also du hast gerade den EventHandler für SizeChanged registriert. Das heißt, dass im Moment deine Größe verändert wird, wenn eine Größenveränderung stattgefunden hat. :confused:

Du solltest die Größe von deiner PictureBox in einer anderen Methode ändern. Wenn du dann das Event(Größe geändert) behandeln willst, dann musst du einen EventHandler für SizeChanged registrieren.

Beispiel:

C#:
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            pictureBox1.SizeChanged += new EventHandler(pictureBox1_SizeChanged);
        }

        void pictureBox1_SizeChanged(object sender, EventArgs e)
        {
            MessageBox.Show("size changed");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.Size = new Size(200, 200);   
        }
    }


Gruß Konstantin
 
Hi,

danke, ich werde das ganze später nochmal ausprobieren. Ich meld mich aufjedenfall nochmal, wenn ich nochmal fragen habe oder es endlich geschafft habe :).

Lg
sailer
 
Hi,

also ich habe es jetzt hinbekommen das ich die größe der Picturebox ändern kann.

Habe es aber jetzt anders realisiert. Funktionieren tut es, hoffe deshalb auch das es stimmt. Also ich kann mit folgendem Code die Picturebox auf einem Panel verschieben und auch die größe ändern.

Mein Code ist folgender:

Code:
private void mouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
                beginMovingPointMouse = new Point(e.X, e.Y);
                beginMovingPointControl = this.Location;

            }
         }


        private void mouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                    geraetPanel.Width = e.X;
                    geraetPanel.Height = e.Y;

                    int deltaX = e.X - beginMovingPointMouse.X;
                    int deltaY = e.Y - beginMovingPointMouse.Y;

                    this.Left += deltaX;
                    this.Top += deltaY;
            }
        }

        private void mouseUp(object sender, MouseEventArgs e)
        {
            isMouseDown = false;
            beginMovingPointMouse = Point.Empty;
            beginMovingPointControl = Point.Empty;
        }

Wie kann ich denn jetzt aber abfragen ob die Maus am Rand der Picturebox ist? Nur dann soll nämlich die Größe verändert werden. Wenn die Maus nicht am Rand ist wird die Picturebox nur verschoben. So wie ich es oben habe macht er mir irgendwie beides aufeinmal. Was nicht stimmt. Die größe soll nur geändert werden wenn der Rand der Picturebox erreicht wurde.

Ich denke das man eine if-Abfrage in das mouseMove Event hinzufügen muss. Stimmt dies?

Ich habe es probiert so zu realisieren. Aber das funktioniert nicht.
Code:
private void mouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
               if (geraetPanel.Left || geraetPanel.Bottom || geraetPanel.Right || geraetPanel.Top)
                {
                    geraetPanel.Width = e.X;
                    geraetPanel.Height = e.Y;
                }
                else
                {
                    int deltaX = e.X - beginMovingPointMouse.X;
                    int deltaY = e.Y - beginMovingPointMouse.Y;

                    this.Left += deltaX;
                    this.Top += deltaY;
                }
            }
        }

Hast du eine Idee?

LG
sailer
 
Hallo,

also wenn ich dich richtig verstanden habe, willst du einmal die PictureBox verschieben in dem du auf diese drauf klickst und dann die Maus bewegst, bist du die Maus wieder los lässt. Und als zweites die Größe der PictureBox verändern wenn du auf den Rand der PictureBox klickst und dann die Maus bewegst?

Hier ist die Lösung für das Verschieben der PictureBox und das Verändern deren Größe durchs klicken auf einen Rand, dessen stärke / breite du selbst verändern kannst. Bei dem Beispiel ist nur eine Größenveränderung von NW nach SO möglich, da die anderen Möglichkeiten zu Exceptions führen (Height/Width <= 0), das kannst du aber bestimmt selber ausarbeiten.

C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace WorkbenchWithMoveableItems
{
    /// <author>konstantin.denerz</author>
    public partial class Workbench : Form
    {
        public Workbench()
        {
            InitializeComponent();
            InitWorkbench();
        }

        /// <summary>
        /// Add mouse and paint event handler to all pictureboxes in the controls container.
        /// </summary>
        private void InitWorkbench()
        {
            foreach (Control control in this.Controls)
            {
                if (control is PictureBox)
                {
                    control.MouseDown+=new MouseEventHandler(pictureBox_MouseDown);
                    control.MouseUp += new MouseEventHandler(pictureBox_MouseUp);
                    control.MouseMove += new MouseEventHandler(pictureBox_MouseMove);
                    control.Paint += new PaintEventHandler(control_Paint);
                }
            }
        }

        /// <summary>
        /// Paint the border.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void control_Paint(object sender, PaintEventArgs e)
        {
            Control control = sender as Control;
            Rectangle rectangle = new Rectangle(1,1, control.Width - ItemBorderWidth, control.Height - ItemBorderWidth);
            LinearGradientBrush brush = new LinearGradientBrush(rectangle, Color.FromArgb(200, 230, 230), Color.FromArgb(230, 230, 245), 30);
            e.Graphics.DrawRectangle(new Pen(brush, ItemBorderWidth), rectangle);
        }

        
        /// <summary>
        /// Holds the border width of each picture box item.
        /// </summary>
        public int ItemBorderWidth
        {
            get { return itemBorderWidth; }
            set { itemBorderWidth = value; }
        } int itemBorderWidth = 6;
        
        /// <summary>
        /// Context that should be used to handle the movement of picture boxes.
        /// </summary>
        Context context;
        
        /// <summary>
        /// Event handler for mouse up event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            if (sender is PictureBox && null != context)
            {
                if (!context.IsMouseDownOnBorder)
                {
                    // move picture box
                    context.MovedControl.Left = MousePosition.X - context.MovedControl.Parent.Left - context.MouseDownPoint.X;
                    context.MovedControl.Top = MousePosition.Y - context.MovedControl.Parent.Top - context.MouseDownPoint.Y;    
                }

                context.MovedControl.Cursor = Cursors.Default;
                context = null;
               
            }
        }

        /// <summary>
        /// Event handler for mouse move event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (null != context)
            {
                if (context.IsMouseDownOnBorder)
                {
                    // resize from north-west to south-east
                    context.MovedControl.Width = e.X;
                    context.MovedControl.Height = e.Y;
                    context.MovedControl.Cursor = Cursors.SizeNWSE;
                }
                else
                {
                    // move
                    context.MovedControl.Left = MousePosition.X - context.MovedControl.Parent.Left - context.MouseDownPoint.X;
                    context.MovedControl.Top = MousePosition.Y - context.MovedControl.Parent.Top - context.MouseDownPoint.Y;
                    context.MovedControl.Cursor = Cursors.SizeAll;
                }
                context.MovedControl.Refresh();
            }   
        }

        private void pictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (sender is PictureBox)
            {
                context = new Context();
                context.MovedControl = sender as Control;
                int x = MousePosition.X - (sender as Control).Parent.Left - (sender as Control).Left;
                int y = MousePosition.Y - (sender as Control).Parent.Top - (sender as Control).Top;
                context.MouseDownPoint = new Point(x, y);
                context.MovedControl.BringToFront();
                // check if you clicked on border of picture box
                GraphicsPath path = new GraphicsPath();
                path.AddRectangle(new Rectangle(new Point(0,0), context.MovedControl.Size));
                GraphicsPath pathWithoutBorder = new GraphicsPath();
                Point location = new Point(ItemBorderWidth, ItemBorderWidth);
                Size size = new Size(context.MovedControl.Width - ItemBorderWidth * 2, context.MovedControl.Height - ItemBorderWidth * 2);
                pathWithoutBorder.AddRectangle(new Rectangle(location, size));
                context.IsMouseDownOnBorder = path.IsVisible(new Point(e.X, e.Y)) && !pathWithoutBorder.IsVisible(new Point(e.X, e.Y));
            }
        }

    }

    class Context
    {
        /// <summary>
        /// Control that should be moved or resized.
        /// </summary>
        public Control MovedControl
        {
            get { return movedControl; }
            set { movedControl = value; }
        } private Control movedControl;

        
        public Point MouseDownPoint
        {
            get { return mouseDownPoint; }
            set { mouseDownPoint = value; }
        } private Point mouseDownPoint = new Point(0, 0);

       
        /// <summary>
        /// True if you clicked on picture box border, else false.
        /// </summary>
        public bool IsMouseDownOnBorder
        {
            get { return isMouseDownOnBorder; }
            set { isMouseDownOnBorder = value; }
        }  private bool isMouseDownOnBorder = false;
    }
}

Gruß Konstantin
 
Zuletzt bearbeitet von einem Moderator:
Hallo Konstantin Denerz

Cooles Script ich Danke auch dafür :)
Habe aber noch eine Frage dazu:
Wie kann man die Picturebox jetzt im Raster nach oben und unten bewegen?

Habe ein paar Sachen versucht aber nix funktioniert :(

Lieben Gruß
TigerCrow
 
Bin zwar nicht Konstantin, aber wie ist die Frage gemeint?
Hab den Quellcode jetzt nicht ausprobiert, aber die PictureBox müsste sich nach links, rechts, oben und nach unten bewegen lassen.
 
Zurück