gpt4 book ai didi

c# - 如何在 PictureBox 中平移图像

转载 作者:太空狗 更新时间:2023-10-29 20:08:04 25 4
gpt4 key购买 nike

我有一个自定义的 PictureBox,它可以使用 MouseWheel 事件进行放大。现在我想给它添加一个平移功能。我的意思是,当 PictureBox 处于缩放状态时,如果用户左键单击并按住单击然后移动鼠标,图像将在 picturebox 内平移。

这是我的代码,但不幸的是它不起作用!我不知道该去哪里找了...

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 事件...我不确定此事件和/或 nxny 是否发生任何事情包含正确的点。

非常感谢任何帮助/提示!

最佳答案

我认为数学是倒退的。像这样尝试:

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 事件中,并且在用户平移时无效。

关于c# - 如何在 PictureBox 中平移图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com