C#实现鼠标裁剪图像功能
本文实例为大家分享了C#实现鼠标裁剪图像的具体代码,供大家参考,具体内容如下
C#的图像裁剪很容易操作,这里给个实现的例子。
关键是需要处理鼠标的事件和一些更新
实现鼠标移动的代码.注意更新不要全部重画,只有选择矩形部分重画
privatevoidForm1_MouseMove(objectsender,MouseEventArgse)
{
if(Track_move)
endpoint=newPoint(e.X,e.Y);
else
{
return;
}
rect1=newRectangle(stpoint.X,stpoint.Y,endpoint.X-stpoint.X,endpoint.Y-stpoint.Y);
Rectangletempr=newRectangle(rect1.X,rect1.Y,rect1.Width+2,rect1.Height+2);
this.Invalidate(tempr);
}
选择结束的处理代码.
privatevoidForm1_MouseUp(objectsender,MouseEventArgse)
{
if(e.Button==MouseButtons.Left&&Track_move==true)
{
Track_move=false;
endpoint=newPoint(e.X,e.Y);
rect1=newRectangle(stpoint.X,stpoint.Y,endpoint.X-stpoint.X,endpoint.Y-stpoint.Y);
Rectanglerectorg=newRectangle(borg.X,borg.Y,image1.Width,image1.Height);
if(rect1.Width<=0)
return;
if(rect1.Height<=0)
return;
if(rectorg.Contains(rect1))
{
Rectanglerectadj=newRectangle(rect1.X-borg.X,rect1.Y-borg.Y,rect1.Width,rect1.Height);
Bitmapcropimge=image1.Clone(rectadj,System.Drawing.Imaging.PixelFormat.Format24bppRgb);
pictureBox2.Image=cropimge;
}
else
{
pictureBox2.Image=null;
}
this.Invalidate();
}
}
程序的整个代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Runtime.InteropServices;
namespaceimageForms
{
staticclassProgram
{
///
///应用程序的主入口点。
///
[STAThread]
staticvoidMain()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(newForm1());
}
}
publicpartialclassForm1:Form
{
privateSystem.Windows.Forms.PictureBoxpictureBox2;
privateSystem.Windows.Forms.Labellabel1;
publicForm1()
{
InitializeComponent();
}
privatevoidpictureBox1_Click(objectsender,EventArgse)
{
}
privatevoidForm1_Load(objectsender,EventArgse)
{
showimg();
}
Bitmapimage1;
privatevoidshowimg()
{
intwd=400;
inthg=200;
intlen=wd*hg*3;
byte[]pdata=newbyte[len];
for(inti=0;i3*wd*(hg/2))
{
pdata[i]=255;
}
else
{
pdata[i]=0;
}
}
try
{
image1=newBitmap(wd,hg,System.Drawing.Imaging.PixelFormat.Format24bppRgb);
for(inty=0;y
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。