c#鼠标选择区域放大

我正在做分形的程序,已经做好了图像,可以通过鼠标放大拖拽图片,想用C#实现pictureBox中用鼠标把图像局部放大,
即首先在pictureBox1中生成了图像,如何用鼠标选中一小块区域,在pictureBox2中显示这一小块区域的放大图像。
望指点,能帮我写一下程序吗?

该回答引用ChatGPT

以下是一个基本的实现示例,假设你有两个PictureBox控件:pictureBox1用于显示原始图像,pictureBox2用于显示局部放大图像。

public partial class Form1 : Form
{
    // 记录鼠标选中的区域
    private Rectangle selection;

    public Form1()
    {
        InitializeComponent();

        // 为pictureBox1注册鼠标事件
        pictureBox1.MouseDown += PictureBox1_MouseDown;
        pictureBox1.MouseMove += PictureBox1_MouseMove;
        pictureBox1.MouseUp += PictureBox1_MouseUp;
    }

    private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        // 保存鼠标按下时的坐标
        selection = new Rectangle(e.Location, new Size());
    }

    private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            // 更新选中区域的大小
            selection.Width = e.X - selection.X;
            selection.Height = e.Y - selection.Y;

            // 在pictureBox1上绘制选中区域的矩形框
            pictureBox1.Refresh();
        }
    }

    private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        // 在pictureBox2中显示局部放大图像
        if (selection.Width > 0 && selection.Height > 0)
        {
            // 计算选中区域相对于pictureBox1的位置和大小
            RectangleF rectF = new RectangleF(
                selection.X / (float)pictureBox1.Width,
                selection.Y / (float)pictureBox1.Height,
                selection.Width / (float)pictureBox1.Width,
                selection.Height / (float)pictureBox1.Height
            );

            // 计算选中区域在原始图像中的位置和大小
            Rectangle sourceRect = new Rectangle(
                (int)(rectF.X * pictureBox1.Image.Width),
                (int)(rectF.Y * pictureBox1.Image.Height),
                (int)(rectF.Width * pictureBox1.Image.Width),
                (int)(rectF.Height * pictureBox1.Image.Height)
            );

            // 截取原始图像中的选中区域
            Bitmap croppedImage = new Bitmap(sourceRect.Width, sourceRect.Height);
            using (Graphics g = Graphics.FromImage(croppedImage))
            {
                g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, croppedImage.Width, croppedImage.Height), sourceRect, GraphicsUnit.Pixel);
            }

            // 在pictureBox2中显示局部放大图像
            pictureBox2.Image = new Bitmap(croppedImage, new Size(pictureBox2.Width, pictureBox2.Height));

            // 清除选中区域
            selection = new Rectangle();
            pictureBox1.Refresh();
        }
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        if (selection.Width > 0 && selection.Height > 0)
        {
            // 绘制选中区域的矩形框
            e.Graphics.DrawRectangle(Pens.Red, selection);
        }
    }
}