Dowemo
0 0 0 0


Question:

I was wondering, once i load an image into a windows form, is there a way for me to allow the user to drag the corners of that image and re-size it?

Currently, i know about the PictureBox.Scale method (but this is deprecated). I also know about PictureBox.Image.Size. Would this mean that each time they re-size i would need to use PictureBox.Image.Size? Also, how do i allow them to grab the image for re-sizing? I guess i'm thinking about paint and how it allows the user to select the image and then re-size it by dragging the corners...

I'm not looking for a full solution - just some pointers in the right direction (Pseudo code or general description to help my thought process would be fine). I'm not quite sure how to approach this problem.

Here is my code so far:

        using (OpenFileDialog ofd = new OpenFileDialog())
        {
            ofd.Title = "Load Image";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                PictureBox pictureBox = new PictureBox();
                pictureBox.Image = new Bitmap(ofd.FileName);
                pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox.Size = pictureBox.Image.Size; 
                panelArea.Controls.Add(pictureBox); 
            }
        }

Best Answer:


Edit: In your case, Hans Passant's method is best. I'll keep my answer up in case you eventually have more complex editing requirements (e.g., dragging multiple shapes)

The interesting part is getting the mouse interaction to work. For now, let's assume you only want to resize by dragging the lower-right hand corner of the image. I would do something like this:

  • Create a UserControl named, e.g, ImageCanvas. Inside this control, do the following:

  • Add a field to keep track of the size/location of the image, perhaps Rectangle imageRect

  • Override the OnPaint method to display your image:

     protected override void OnPaint(PaintEventArgs e)
     {
         e.Graphics.DrawImage(image, imageRect);
     }
  • Add a field to keep track of when the user is resizing the image, say bool isDraggingSize

  • Override OnMouseDown, and OnMouseUp. Set or clear isDraggingSize when the mouse button goes down or up, respectively.

  • Override OnMouseMove to do the following:

    • Set the cursor: If isDraggingSize or the mouse pointer is close to the lower right corner of the image, set Cursor = Cursors.SizeNWSE; otherwise, set Cursor = Cursors.Default.

    • If isDraggingSize, change the imageSize field based on the mouse location. Call Invalidate(), or Refresh() if necessary, to update the display.

  • Play around with it, and fix all the little details -- like deciding what happens when the user tries to resize the image larger than the control, and how to get rid of flickering.




  • Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs