简体   繁体   中英

Convert PictureBox Selection Rectangle according to SizeMode

I have two PictureBoxes pbOriginal and pbFace. After Selecting a "face" from an image in pbOriginal I clone the rectangle selection and place it into pbFace. However, Because pbOriginal is using SelectionMode=Stretch the actual area being copied is not the same as the area being selected.

How do I convert the coordinates of the Rectangle so that they truly reflect the coordinates of the Stretched Image?

Here is an example that draws the second rectangle right along as you draw the first one..:

在此处输入图片说明

Point mDown = Point.Empty;
Point mCurr = Point.Empty;

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{   mDown = e.Location;  }

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
       { mCurr = e.Location; pictureBox1.Invalidate(); }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Rectangle r = new Rectangle(mDown.X, mDown.Y, mCurr.X - mDown.X, mCurr.Y - mDown.Y);
    e.Graphics.DrawRectangle(Pens.Orange, r);
    pictureBox2.Invalidate();
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    if (pictureBox2.Image == null) return;

    float stretch1X = 1f * pictureBox1.Image.Width / pictureBox1.ClientSize.Width;
    float stretch1Y = 1f * pictureBox1.Image.Height / pictureBox1.ClientSize.Height;

    int x = (int)(mDown.X * stretch1X);
    int y = (int)(mDown.Y * stretch1Y);
    int x2 = (int)(mCurr.X * stretch1X);
    int y2 = (int)(mCurr.Y * stretch1Y);

    Rectangle r = new Rectangle(x, y, x2 - x, y2 - y);
    e.Graphics.DrawRectangle(Pens.Orange, r);
}

Note that it assumes that you are drawing top-left to bottom-right..

If you want to copy the selection you can use the same factors and the same Rectangle as the source for a DrawImage call:

float stretch1X = 1f * pictureBox1.Image.Width / pictureBox1.ClientSize.Width;
float stretch1Y = 1f * pictureBox1.Image.Height / pictureBox1.ClientSize.Height;

Point pt = new Point((int)(mDown.X * stretch1X), (int)(mDown.Y * stretch1Y));
Size sz = new Size((int)((mCurr.X - mDown.X) * stretch1X), 
                   (int)((mCurr.Y - mDown.Y) * stretch1Y));


Rectangle rSrc = new Rectangle(pt, sz);
Rectangle rDest= new Rectangle(Point.Empty, sz);

Bitmap bmp = new Bitmap(sz.Width, sz.Height);
using (Graphics G = Graphics.FromImage(bmp))
    G.DrawImage(pictureBox1.Image, rDest, rSrc , GraphicsUnit.Pixel);
pictureBox2.Image = bmp;

You may want to code the MouseUp event to store the finla mCurr position and trgger the copying..

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