日期:2014-05-18  浏览次数:20955 次

实现PhotoShop背景和图像拖动
简单实现一下PS中图像拖动功能以及背景问题(背景并非图像直接添加),与大家共享一下呵呵!
先看效果图



所有代码如下:
[code=C#][/code]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 = endP