因项目需要,要实现一个类似于QQ上传图片的那个截图功能。所以研究了一番。
创建一个位图,得到选择位图的图片。
public Bitmap GetSelectionImage()
{
Bitmap bitmap = new Bitmap(554, 322);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
Brush brush = null;
brush = new SolidBrush(Color.Black);
int w = mBackgroundImage.Width;
int h = mBackgroundImage.Height;
int x = (Width - w) / 2;
int y = (Height - h) / 2;
mDragRect.Offset(-x, -y);
g.DrawImage(mBackgroundImage, new Rectangle(0, 0, 554, 322), mDragRect, GraphicsUnit.Pixel);
g.Dispose();
}
}
然后要能随着鼠标的移动,框也要跟着动,模拟鼠标移动事件。 private void OnMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mPrevX = e.Location.X;
mPrevY = e.Location.Y;
int x = e.Location.X;
int y = e.Location.Y;
if (mDragRect.Contains(x, y))
{
mDrag = true;
}
}
}
private void OnMouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (mDrag)
{
mOffsetX = e.Location.X - mPrevX;
mOffsetY = e.Location.Y - mPrevY;
mPrevX = e.Location.X;
mPrevY = e.Location.Y;
mDragRect.Offset(mOffsetX, mOffsetY);
if (mDragRect.Left < 0)
{
mDragRect.X = 0;
}
if (mDragRect.Top < 0)
{
mDragRect.Y = 0;
}
if (mDragRect.Left >= Width - 554)
{
mDragRect.X = Width - 555;
}
if (mDragRect.Top >= Height - 322)
{
mDragRect.Y = Height - 333;
}
this.Invalidate();
}
}
private void OnMouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
mDrag = false;
}
把图画到背景上
public void SetBackgroundImageFile(string image)
{
mBackgroundImage = Image.FromFile(image);
mFileName = System.IO.Path.GetFileName(image);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
BufferedGraphics bg = mContext.Allocate(this.CreateGraphics(), this.ClientRectangle);
DrawBackground(bg);
DrawDragSelection(bg);
bg.Render(e.Graphics);
bg.Dispose();
}
private void DrawBackground(BufferedGraphics bg)
{
Graphics g = bg.Graphics;
g.Clear(mBackgroundClr);
//g.Clear(Color.FromArgb(255,255,255));
g.Clear(mForegroundColor);
if (mBackgroundImage != null)
{
int w = mBackgroundImage.Width;
int h = mBackgroundImage.Height;
int x = (Width - w) / 2;
int y = (Height - h) / 2;
g.DrawImage(mBackgroundImage, x, y);
}
}
效果图如下 :