C#中的PictureBox鼠标滚轮缩放和滚动

4

我想创建一个pictureBox,可以像谷歌地图一样放大/缩小到光标位置。

以下是一些代码:

int viewRectWidth;
int viewRectHeight;
public float zoomshift = 0.05f;
int xForScroll;
int yForScroll;
float zoom = 1.0f;
public float Zoom
{
  get { return zoom; }
  set
  {
    if (value < 0.001f) value = 0.001f;
    zoom = value;
    displayScrollbar();
    setScrollbarValues();
    Invalidate();
  }
}
Size canvasSize = new Size(60, 40);
public Size CanvasSize
{
  get { return canvasSize; }
  set
  {
    canvasSize = value;
    displayScrollbar();
    setScrollbarValues();
    Invalidate();
  }
}
Bitmap image;
public Bitmap Image
{
  get { return image; }
  set
  {
    image = value;
    displayScrollbar();
    setScrollbarValues();
    Invalidate();
  }
}
InterpolationMode interMode = InterpolationMode.HighQualityBilinear;
public InterpolationMode InterpolationMode
{
  get { return interMode; }
  set { interMode = value; }
}
public ZoomablePictureBox()
{
  InitializeComponent();
  this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | 
                ControlStyles.ResizeRedraw | ControlStyles.UserPaint | 
                ControlStyles.DoubleBuffer, true);
}
protected override void OnPaint(PaintEventArgs e)
{
  base.OnPaint(e);
  if(image != null)
  {
    Rectangle srcRect, distRect;
    Point pt = new Point((int)(hScrollBar1.Value / zoom), (int)(vScrollBar1.Value / zoom));
    if (canvasSize.Width * zoom < viewRectWidth) 
      srcRect = new Rectangle(0, 0, canvasSize.Width, canvasSize.Height);
    else srcRect = new Rectangle(pt, new Size((int)(viewRectWidth / zoom), (int)(viewRectHeight / zoom)));
    distRect = new Rectangle((int)(-srcRect.Width / 2), -srcRect.Height / 2, srcRect.Width, srcRect.Height);

    Matrix mx = new Matrix();
    mx.Scale(zoom, zoom);
    mx.Translate(viewRectWidth / 2.0f, viewRectHeight / 2.0f, MatrixOrder.Append);

    Graphics g = e.Graphics;
    g.InterpolationMode = interMode;
    g.Transform = mx;
    g.DrawImage(image, distRect, srcRect, GraphicsUnit.Pixel);
  }
}

现在我需要鼠标滚轮事件来缩放并滚动到鼠标指针位置,但我就是无法弄清楚应该将滚动条设置为哪些值的公式。

private void onMouseWheel(object sender, MouseEventArgs e)
{
  if (ModifierKeys == Keys.Control)
  {
    this.Zoom += e.Delta / 120 * this.zoomshift;
    vScrollBar1.Value = ?;
    hScrollBar1.Value = ?;
  }
}

任何帮助都将不胜感激。
敬礼,Tomas

如果您要以这种方式绘制大型图片,您将遇到性能问题,请参见此非常新的问题:http://stackoverflow.com/q/23733405/1997232。 - Sinatr
1个回答

0
如果您想保持滚动条的相对位置不变,我认为以下方法应该有效:
float oldvMax = vScrollBar1.Maximum;
int oldvValue = vScrollBar1.Value;
float oldhMax = hScrollBar1.Maximum;
int oldhValue = hScrollBar1.Value;
this.Zoom += e.Delta / 120 * this.zoomshift;
vScrollBar1.Value = (int)((oldvValue / oldvMax) * vScrollBar1.Maximum);
hScrollBar1.Value = (int)((oldhValue / oldhMax) * hScrollBar1.Maximum);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接