在光标之后的第二个图片框中缩放图像

时间:2019-08-04 13:59:02

标签: c# image zoom picturebox

我有一个包含图像(1280 X 720)的图片框,我想创建第二个图片框,其中包含以光标为中心的图像的缩放版本(例如,将光标周围的40 X 40正方形放大为在一个120 X 120方形的图片框中)实时实时跟随光标(如果可能的话,在图片框的中间有一个十字线,可以更好地显示光标的位置)。

private void Button1_Click(object sender, EventArgs e)
     {
         openFileDialog1.Filter = "All jpg files (*.jpg)|*.jpg";
         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             Bitmap img = new Bitmap(openFileDialog1.FileName);
             double imageHeight = img.Height;
             double imageWidth = img.Width;
             pictureBox1.Image = img;

         }
     }
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
     {
         int xupleft = e.X - 20;
         int yupleft = e.Y - 20;

         Rectangle myrectangle = new Rectangle(xupleft, yupleft, 40, 40);

         pictureBox2.Image = pictureBox1.Image;

     }

1 个答案:

答案 0 :(得分:0)

这是我在评论中描述的布局的简单示例:

  • 两个PictureBox均在面板中嵌套
  • 第一个处于Zoom模式,并且在加载文件时,其大小将进行调整以避免侧面出现空白条纹。其父面板用于重置为允许的最大大小。
  • 第二个处于AutoSize模式,其父面板用于1)隐藏外部部分和2)计算偏移量以使图像居中。

这是pbox1的简单Paint事件:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Size sz = pictureBox1.ClientSize;
    Point pt = pictureBox1.PointToClient(Control.MousePosition);
    e.Graphics.DrawLine(Pens.OrangeRed, pt.X, 0, pt.X, sz.Height);
    e.Graphics.DrawLine(Pens.OrangeRed, 0, pt.Y, sz.Width, pt.Y);
}

这里是MouseMove触发器Paint并移动pbox2:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    pictureBox1.Invalidate();

    float f = 1f * pictureBox2.ClientSize.Width / pictureBox1.ClientSize.Width;
    Size s2 = pictureBox2.Parent.ClientSize;
    Point p2 = Point.Round(new PointF(s2.Width/2 - e.X * f , s2.Height/2 - e.Y * f ));
    pictureBox2.Location = p2;
}

文件加载有点棘手,因为它需要分析图像和pbox的长宽比:

void loadFile(string fileName)
{
    if (File.Exists(fileName))
    {
        pictureBox1.Size = panel1.ClientSize;
        pictureBox1.Location = Point.Empty;

        pictureBox1.Image = Image.FromFile(fileName);
        pictureBox2.Image = Image.FromFile(fileName);
        pictureBox2.Location = Point.Empty;
    }
    Size csz = pictureBox1.ClientSize;
    Size isz = pictureBox1.Image.Size;
    float iar = 1f * isz.Width / isz.Height;  // aspect..
    float car = 1f * csz.Width / csz.Height;  //..ratios
    if (iar < car)
    {
        pictureBox1.ClientSize = new Size((int)(pictureBox1.ClientSize.Height * iar), 
                                          pictureBox1.ClientSize.Height);
    }
    else if (iar > car)
    {
        pictureBox1.ClientSize = new Size((pictureBox1.ClientSize.Width,
                                          (int)(pictureBox1.ClientSize.Width / iar));
    }
}

请注意,在加载新图像之前,应Dispose个先前图像!同样,之后将pbox2.SizeMode设置为Autosize的人可以将其设置为Zoom并向上或向下缩放其Size来放大或缩小,如果保持宽高比不变。

结果:

enter image description here