效果图:
http://s12/mw690/621e24e2tx6CIEaC3wv5b&690截图、拖拽矩形图片 局部放大 模仿淘宝" TITLE="C# 截图、拖拽矩形图片 局部放大 模仿淘宝" />
总共就两个控件,大的是pictureBox1,小的是pictureBox2:
需要说一下的是,bitmap.Clone的方法如果操作不当会导致内存不足的错误。当鼠标截图的时候,截图的坐标大于边界的时候,就会内存不足的错误,所以解决办法就是拖到边界的时候,就不再扩大了,鼠标松开的时候截图的区域就是边界,试一下就知道;还有就是及时利用垃圾回收机制GC.Collect()清理垃圾。
哦对了,图片自己找一下吧,别忘了自己手动打一遍
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace PicZoom
{
public
partial class Form1 : Form
{
public static int i = 0;
private Point m_ptStart = new Point(0, 0);
private Point m_ptEnd = new Point(0, 0);
private bool m_bMouseDown = false;
private float xRate, yRate, realX1, realY1, realX2, realY2;
int pLeft = 0;
int pTop = 0;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs
e)
{
if (pictureBox1.HasChildren)
{
for (int i = 0; i < pictureBox1.Controls.Count;
i++)
{
pictureBox1.Controls.RemoveAt(0);
}
}
if (e.Button != MouseButtons.Left)
{
return;
}
m_ptEnd = new Point(e.X, e.Y);
this.pictureBox1.Refresh();
realX1 = e.X * xRate;
realY1 = e.Y * yRate;
if (!m_bMouseDown)
{
m_ptStart = new Point(e.X, e.Y);
m_ptEnd = new Point(e.X, e.Y);
}
m_bMouseDown = !m_bMouseDown;
}
private void pictureBox1_Paint(object sender, PaintEventArgs
e)
{
if (m_ptEnd.X - m_ptStart.X < 0 || m_ptEnd.Y -
m_ptStart.Y < 0)
{
return;
}
if (m_ptEnd.X - m_ptStart.X >= 100)
{
m_ptEnd.X = m_ptStart.X + 100;
}
if (m_ptEnd.Y - m_ptStart.Y >= 100)
{
m_ptEnd.Y = m_ptStart.Y + 100;
}
e.Graphics.DrawRectangle(System.Drawing.Pens.Blue, m_ptStart.X,
m_ptStart.Y, m_ptEnd.X - m_ptStart.X, m_ptEnd.Y -
m_ptStart.Y);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs
e)
{
int eX = 0, eY = 0;
if (e.Button != MouseButtons.Left)
{
return;
}
if (e.X - m_ptStart.X >= 100)
{
if (e.X >= pictureBox1.Width - 1)
{
if (pictureBox1.Width - m_ptStart.X - 1 > 100)
{
eX = m_ptStart.X + 100;
}
else
{
eX = pictureBox1.Width - 1;
}
}
else