缩放图形而不滚动

时间:2017-01-29 20:33:32

标签: c# .net winforms graphics

我有一个用户控件,我使用ScaleTransform()来实现缩放。

但是,为了在缩放后将中心内容保持在中心,还需要滚动。例如,如果我放大(使事情更大),X和Y原点应该增加,以便大多数内容不会向下和向右移动。 (也就是说,当我放大时,一些内容应该消失在左侧和顶部。)

有没有人计算出在X和Y方向上滚动多少以响应缩放?

例如:

e.Graphics.ScaleTransform(2.0F, 2.0F);
e.Graphics.TranslateTransform(?, ?);

我对TranslateTransform()的论点是什么,以便内容的中心部分保持在中心?

注意:我没有显示图像。我正在将图形内容绘制到用户控件的表面。

或许还有更简单的方法?

2 个答案:

答案 0 :(得分:2)

这应该有效,我无法想象任何更简单的方法;它假设您已决定缩放的中心。我选择以小组为中心绘制:

float zoom = 1f;

private void drawPanel1_Paint(object sender, PaintEventArgs e)
{
    Point c = new Point(drawPanel1.ClientSize.Width / 2, drawPanel1.ClientSize.Height / 2);

    // a blue sanity check for testing
    e.Graphics.FillEllipse(Brushes.DodgerBlue, c.X - 3, c.Y - 3, 6, 6);

    // the offsets you were looking for:
    float ox = c.X * ( zoom - 1f);
    float oy = c.Y * ( zoom - 1f);

    // first move and then scale
    e.Graphics.TranslateTransform(-ox, -oy);
    e.Graphics.ScaleTransform(zoom, zoom);

     // now we can draw centered around our point c
    Size sz = new Size(300, 400);
    int count = 10;
    int wx = sz.Width  / count;
    int wy = sz.Height / count;

    for (int i = 0; i < count; i++)
    {
        Rectangle r = new Rectangle(c.X - i * wx / 2 , c.Y - i * wy / 2, i * wx, i * wy );
        e.Graphics.DrawRectangle(Pens.Red, r );
    }
}

enter image description here

请注意移动和缩放的顺序!

答案 1 :(得分:0)

我猜你正在使用一些不同的界面,但在我的情况下,这就是完成工作的原因(在鼠标滚轮事件发生后将鼠标放在它上面的原始位置):

private void DrawPb_MouseWheel(object sender, MouseEventArgs e)
    {
        // e contains current mouse location and the wheel direction
        int wheelDirection = e.Delta / Math.Abs(e.Delta); // is 'in' or 'out' (1 or -1).
        double factor = Math.Exp(wheelDirection * Constants.ZoomFactor); // divide or multiply
        double newX = e.X - e.X / factor; // what used to be x is now newX
        double newY = e.Y - e.Y / factor; // same for y
        Point offset = new Point((int)(-newX), (int)(-newY)); // the offset of the old point to it's new location
        Graph.AddOffset(offset); // apply offset
    }
相关问题