簡體   English   中英

根據SizeMode轉換PictureBox選擇矩形

[英]Convert PictureBox Selection Rectangle according to SizeMode

我有兩個PictureBoxes pbOriginal和pbFace。 從pbOriginal中的圖像中選擇“面部”后,我克隆矩形選擇並將其放入pbFace中。 但是,由於pbOriginal使用的是SelectionMode=Stretch因此實際復制的區域與所選區域不同。

如何轉換矩形的坐標,以使其真正反映拉伸圖像的坐標?

這是一個示例,它在繪制第一個矩形的同時向右繪制第二個矩形:

在此處輸入圖片說明

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

請注意,它假定您是從左上方繪制到右下方。

如果要復制選擇,則可以使用與DrawImage調用的源相同的因子和相同的Rectangle

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;

您可能需要對MouseUp事件進行編碼,以存儲finla mCurr位置並觸發復制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM