在PS中我们会看到图像拖动过程中,它的背景是删格状的,如何实现呢?
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.Image = (Image)src;
pictureBox1.Width = src.Width;
pictureBox1.Height = src.Height;
BackGround();
}
#region 全局变量定义
private Bitmap src = new Bitmap("0.jpg");//原始图像
private Point startPoint, endPoint;//定义鼠标起始点
private Bitmap bac = null;//定义背景图像
private Bitmap tempBac = null;//定义临时背景变量
#endregion
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
startPoint.X = e.X;
startPoint.Y = e.Y;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
endPoint.X = e.X;
endPoint.Y = e.Y;
if (e.X > 0 && e.X < pictureBox1.Width && e.Y > 0 && e.Y < pictureBox1.Height)
{
pictureBox1.Image = (Image)TempBitmap(src,tempBac ,bac );
}
}
pictureBox1.Refresh();
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
startPoint.X = 0;
startPoint.Y = 0;
endPoint.X = 0;
endPoint.Y = 0;
}
#region 函数定义
//绘制背景
private void BackGround()
{
bac = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(bac);
bool sWhite = true;
for (int h = 0; h < pictureBox1.Height; h += 10)
{
for (int w = 0; w < pictureBox1.Width; w += 10)
{
if (sWhite)
{
g.FillRectangle(Brushes.White, new Rectangle(new Point(w, h), new Size(10, 10)));
sWhite = false;
}
else
{
g.FillRectangle(Brushes.Gray, new Rectangle(new Point(w, h), new Size(10, 10)));
sWhite = true;
}
}
if (sWhite == true)
{
sWhite = false;
}
else
{
sWhite = true;
}
}
g.Dispose();
pictureBox1.BackgroundImage = (Image)bac;
}
//平移变化函数
private Bitmap TempBitmap(Bitmap src,Bitmap dst,Bitmap bac)
{
int x = endPoint.X - startPoint.X;
int y = endPoint.Y - startPoint.Y;
dst = new Bitmap(bac);
Bitmap a = null;
Graphics g = Graphics.FromImage(dst);
if (x >= 0 && y >= 0)
{
a = src.Clone(new Rectangle(0, 0, src.Width - Math.Abs(x), src.Height - Math.Abs(y)), src.PixelFormat);
g.DrawImage(a, x, y);
}
else if(x<0&&y<0)
{
a = src.Clone(new Rectangle(Math.Abs(x), Math.Abs(y), src.Width - Math.Abs(x), src.Height - Math.Abs(y)), src.PixelFormat);
g.DrawImage(a, 0, 0);
}
else if (x > 0 && y < 0)
{
a = src.Clone(new Rectangle(0, Math.Abs(y), src.Width - Math.Abs(x), src.Height - Math.Abs(y)), src.PixelFormat);
g.DrawImage(a, x, 0);
}
else if(x<0&&y>0)
{
a = src.Clone(new Rectangle(Math .Abs (x), 0, src.Width - Math.Abs(x), src.Height - Math.Abs(y)), src.PixelFormat);
g.DrawImage(a, 0, y);
}
g.Dispose();
return dst;
}
#endregion
}
}
效果图如下: