如何平移内PictureBox的Image [英] How to pan Image inside PictureBox
问题描述
我有一个自定义的图片框
可以使用鼠标滚轮
事件放大。现在我想一个平移功能添加到它。我的意思是,当图片框处于放大状态,如果用户离开点击并保持点击,然后移动鼠标,图像将在PictureBox内平移。
I have a custom PictureBox
which can zoom in using MouseWheel
event. Now I want to add a panning feature to it. I mean when PictureBox is in zoomed state, if user left clicks and holds the click then move the mouse, the image would pan within the picturebox.
下面是我的代码,但遗憾的是它不工作!我不知道去哪里找了...
Here is my code but unfortunately it does not work! I don't know where to look anymore...
private Point _panStartingPoint = Point.Empty;
private bool _panIsActive;
private void CurveBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Focus();
_panIsActive = true;
_panStartingPoint = e.Location;
}
}
private void CurveBox_MouseUp(object sender, MouseEventArgs e)
{
_panIsActive = false;
}
private void CurveBox_MouseLeave(object sender, EventArgs e)
{
_panIsActive = false;
}
private void CurveBox_MouseMove(object sender, MouseEventArgs e)
{
if(_panIsActive && IsZoomed)
{
var g = CreateGraphics(); //Create graphics from PictureBox
var nx = _panStartingPoint.X + e.X;
var ny = _panStartingPoint.Y + e.Y;
var sourceRectangle = new Rectangle(nx, ny, Image.Width, Image.Height);
g.DrawImage(Image, nx, ny, sourceRectangle, GraphicsUnit.Pixel);
}
}
我怀疑的的MouseMove
事件......我不知道如果有什么在这个事件发生和/或 NX
和纽约
确实包含正确的点。
I am suspecting the MouseMove
event...I am not sure if anything happens in this event and/or nx
and ny
does contain correct point.
任何帮助/提示,真的是appriciated!
Any helps/tips is really appriciated!
推荐答案
我觉得数学倒退。尝试这样的:
I think the math is backwards. Try it like this:
private Point startingPoint = Point.Empty;
private Point movingPoint = Point.Empty;
private bool panning = false;
void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
panning = true;
startingPoint = new Point(e.Location.X - movingPoint.X,
e.Location.Y - movingPoint.Y);
}
void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
panning = false;
}
void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
if (panning) {
movingPoint = new Point(e.Location.X - startingPoint.X,
e.Location.Y - startingPoint.Y);
pictureBox1.Invalidate();
}
}
void pictureBox1_Paint(object sender, PaintEventArgs e) {
e.Graphics.Clear(Color.White);
e.Graphics.DrawImage(Image, movingPoint);
}
您不能处理您的图形对象,的createGraphics只是暂时绘图反正(减少会删除它)让我感动的绘制代码的Paint事件和我只是作为无效用户平移。
You aren't disposing your graphic object, and CreateGraphics is just a temporary drawing anyway (minimizing would erase it) so I moved the drawing code to the Paint event and am just invalidating as the user is panning.
这篇关于如何平移内PictureBox的Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!