PictureBox缩放并滚动鼠标滚轮C#

时间:2014-05-21 11:45:06

标签: c# winforms

我正在尝试创建可以放大/缩小光标的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 = ?;
  }
}

任何帮助将不胜感激。

此致,托马斯

1 个答案:

答案 0 :(得分: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);
相关问题