要實(shí)現(xiàn)圖像局部放大效果,可以使用PictureBox控件和Mouse事件來實(shí)現(xiàn)。以下是一個簡單的示例代碼:
首先,在窗體中添加一個PictureBox控件,并加載要顯示的圖像。
添加MouseHover和MouseLeave事件處理程序,用來實(shí)現(xiàn)當(dāng)鼠標(biāo)懸停在PictureBox上時,顯示局部放大的效果。
private void pictureBox1_MouseHover(object sender, EventArgs e)
{
// 獲取鼠標(biāo)當(dāng)前位置
Point location = pictureBox1.PointToClient(Cursor.Position);
// 計算局部放大的區(qū)域
int zoomSize = 100; // 放大倍數(shù)
int x = location.X - zoomSize / 2;
int y = location.Y - zoomSize / 2;
int width = zoomSize;
int height = zoomSize;
// 創(chuàng)建一個新的圖像,用于顯示局部放大的效果
Bitmap zoomedImage = new Bitmap(zoomSize, zoomSize);
using (Graphics g = Graphics.FromImage(zoomedImage))
{
g.DrawImage(pictureBox1.Image, new Rectangle(0, 0, zoomSize, zoomSize), new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
}
// 在新的圖像上繪制一個邊框
using (Graphics g = Graphics.FromImage(zoomedImage))
{
g.DrawRectangle(Pens.Red, 0, 0, zoomSize - 1, zoomSize - 1);
}
// 在窗體上顯示局部放大的圖像
Form zoomForm = new Form();
PictureBox zoomPictureBox = new PictureBox();
zoomPictureBox.Image = zoomedImage;
zoomPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
zoomForm.Controls.Add(zoomPictureBox);
zoomForm.StartPosition = FormStartPosition.Manual;
zoomForm.Location = new Point(Cursor.Position.X + 10, Cursor.Position.Y + 10);
zoomForm.Show();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
// 關(guān)閉局部放大的圖像窗口
foreach (Form form in Application.OpenForms)
{
if (form.Name == "zoomForm")
{
form.Close();
return;
}
}
}
在上面的示例中,當(dāng)鼠標(biāo)懸停在PictureBox上時,會顯示一個局部放大的圖像窗口,當(dāng)鼠標(biāo)離開PictureBox時,會關(guān)閉局部放大的圖像窗口。可以根據(jù)實(shí)際需求對放大倍數(shù)和顯示位置進(jìn)行調(diào)整。