廢話不多說,直接上圖看效果,左上角是原圖片大小,右邊是局部放大的效果 主要代碼貼在下麵,picBox是原圖控制項名,picBox_Show是放大控制項名 private void picBox_Paint(object sender, PaintEventArgs e) { if (isMove == ...
廢話不多說,直接上圖看效果,左上角是原圖片大小,右邊是局部放大的效果
主要代碼貼在下麵,picBox是原圖控制項名,picBox_Show是放大控制項名
private void picBox_Paint(object sender, PaintEventArgs e)
{
if (isMove == true)
{
Graphics g = e.Graphics;
/*畫長方形*/
int _x = movedPoint_X - rect_W / 2;
int _y = movedPoint_Y - rect_H / 2;
_x = _x < 0 ? 0 : _x;
_y = _y < 0 ? 0 : _y;
_x = _x >= picBox.Width - rect_W ? picBox.Width - rect_W - 3 : _x; //減3px的目的就是為了讓長方形的邊框不會剛好被picBox的邊框擋住了
_y = _y >= picBox.Height - rect_H ? picBox.Height - rect_H - 3 : _y;
Rectangle rect = new Rectangle(_x, _y, rect_W, rect_H);
g.DrawRectangle(pen, rect);
// g.FillRectangle(brush, rect);
///*填充網格*/
int x1, x2, y1, y2;
x1 = x2 = _x;
y1 = y2 = _y;
x2 += rect_W;
for (int i = 1; i < rowGridCount; i++)
{
y1 += gridSize;
y2 += gridSize;
g.DrawLine(pen, x1, y1, x2, y2);
}
x1 = x2 = _x;
y1 = y2 = _y;
y2 += rect_H;
for (int j = 1; j < columnGridCount; j++)
{
x1 += gridSize;
x2 += gridSize;
g.DrawLine(pen, x1, y1, x2, y2);
}
/*裁剪圖片*/
if (picBox_Show.Image != null)
{
picBox_Show.Image.Dispose();
}
Bitmap bmp = (Bitmap)picBox.Image;
//縮放比例
double rate_W = Convert.ToDouble(bmp.Width) / picBox.Width;
double rate_H = Convert.ToDouble(bmp.Height) / picBox.Height;
Bitmap bmp2 = bmp.Clone(new Rectangle(Convert.ToInt32(rate_W * _x), Convert.ToInt32(rate_H * _y), Convert.ToInt32(rate_W * rect_W), Convert.ToInt32(rate_H * rect_H)), picBox.Image.PixelFormat);
picBox_Show.Image = bmp2;
picBox_Show.SizeMode = PictureBoxSizeMode.Zoom;
picBox_Show.Visible = true;
isMove = false;
}
}
//Paint事件中處理邏輯:當滑鼠移動在圖片的某個位置時,我們需要繪個長方形區域,同時顯示局部放大圖片(picBox_Show)。當執行picBox.Refresh()方法時將觸發該事件。
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
picBox.Focus(); //否則滾輪事件無效
isMove = true;
movedPoint_X = e.X;
movedPoint_Y = e.Y;
picBox.Refresh();
}
//滑鼠移開後,局部顯示圖片(picBox_Show)隱藏,picBox繪製的長方形也要去掉,最簡單的就是調用Refresh()方法了。
void picBox_Show_MouseWheel(object sender, MouseEventArgs e)
{
double scale = 1;
if (picBox_Show.Height > 0)
{
scale = (double)picBox_Show.Width / (double)picBox_Show.Height;
}
picBox_Show.Width += (int)(e.Delta * scale);
picBox_Show.Height += e.Delta;
}
bool isMove = false;
//滑鼠移動後點的坐標
int movedPoint_X, movedPoint_Y;
//畫筆顏色
Pen pen = new Pen(Color.FromArgb(91, 98, 114));
HatchBrush brush = new HatchBrush(HatchStyle.Cross, Color.FromArgb(91, 98, 114), Color.Empty); //使用陰影畫筆畫網格
//選取區域的大小
const int rect_W = 80;
const int rect_H = 60;
//網格邊長:5px 一格
const int gridSize = 2;
//網格的行、列數
int rowGridCount = rect_H / gridSize;
int columnGridCount = rect_W / gridSize;
private void picBox_MouseLeave(object sender, EventArgs e)
{
picBox_Show.Visible = false;
picBox.Refresh();
picBox_Show.Width = 400;
picBox_Show.Height = 300;
}