围绕鼠标点缩放所有者绘制窗口

I have an owner-draw PictureBox (picGrid) and I want to allow the user to zoom using the mouse wheel. That part is easy, but when zooming I want to automatically scroll so that the logical point under the mouse is still the logical point under the mouse after the zoom.

Here's what I have so far. It's right in some cases but wrong in most. XScroll and YScroll are my scroll positions and will be used to set the scroll bar (in addition to offset the image).

/// <summary>
/// Sets the current zoom percent.
/// </summary>
/// <param name="percent">The percent that the zoom should be set (100 == no zoom).</param>
/// <param name="x">X coordinate of the mouse in pixels.</param>
/// <param name="y">Y coordinate of the mouse in pixels.</param>
public void SetZoom(int percent, int x, int y)
{
    // This would translate mouse coordinate to logical coordinates
    // but doesn't appear to be needed.
    //TranslateCoordinates(ref x, ref y);

    // Calculate new scale (1.0f == 1:1 scaling)
    float newDrawScale = (float)percent / 100;

    // Enforce zoom limits
    if (newDrawScale < 0.1f)
        newDrawScale = 0.1f;
    else if (newDrawScale > 1500.0f)
        newDrawScale = 1500.0f;

    if (newDrawScale != DrawScale)
    {
        DrawScale = newDrawScale;

        // Here's the part I'm having trouble with
        // Scroll towards x, y
        float delta = (DrawScale - 1f);
        XScroll = (x * delta);
        YScroll = (y * delta);

        UpdateScrollbars();
        picGrid.Invalidate();
    }
}

如何计算新的滚动位置,以便在缩放后鼠标指针下仍保留相同的逻辑点?

评论