目标:实现图片放大缩小和移动
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
namespace 图片放大缩小
{
public partial class Form1 : Form
{
int xPos;
int yPos;
bool MoveFlag;
public Form1()
{
InitializeComponent();
this.MouseWheel += new MouseEventHandler(MainForm_MouseWheel);
}
byte[] picturebytes;
Bitmap bmap;
private void Button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "所有图片文件(*.bmp/*.jpg/*.gif)|*.*|Jpeg 文件(*.jpg)|*.jpg|Bitmap 文件(*.bmp)|*.bmp|gif 文件(*.gif)|*.gif";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName;//文件路径
System.IO.FileStream fs = new FileStream(fullpath, FileMode.Open);
picturebytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
picturebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
MemoryStream ms = new MemoryStream(picturebytes);
bmap = new Bitmap(ms);
pictureBox1.Image = bmap;
}
else
{
MessageBox.Show("图片打开失败");
}
}
private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.pictureBox1.Focus();
MoveFlag = true;//已经按下.
xPos = e.X;//当前x坐标.
yPos = e.Y;//当前y坐标.
}
float Scale = 1;
private void MainForm_MouseWheel(object sender, MouseEventArgs e)
{
// MessageBox.Show("滚动事件已被捕捉");
//System.Drawing.Size t = bmap.Size;
//t.Width += e.Delta;
//t.Height += e.Delta;
//bmap.Width = t.Width;
//bmap.Height = t.Height;
//bmap.Width= t.Width;
//System.Drawing.Size t = pictureBox1.Size;
//t.Width += e.Delta;
//t.Height += e.Delta;
//pictureBox1.Width = t.Width;
//pictureBox1.Height = t.Height;
if (e.Delta < 0)
{
this.pictureBox1.Width = this.pictureBox1.Width * 9 / 10;
this.pictureBox1.Height = this.pictureBox1.Height * 9 / 10;
}
else
{
this.pictureBox1.Width = this.pictureBox1.Width * 11 / 10;
this.pictureBox1.Height = this.pictureBox1.Height * 11 / 10;
}
}
private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
{
//鼠标已经抬起
MoveFlag = false;
}
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (MoveFlag)
{
pictureBox1.Left += Convert.ToInt16(e.X - xPos);//设置x坐标.
pictureBox1.Top += Convert.ToInt16(e.Y - yPos);//设置y坐标.
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}