使用Graphics.ScaleTransform时,笔的缩放比例不正确

时间:2012-05-07 12:24:01

标签: c# winforms graphics scaletransform

在我的Graphics.ScaleTransform()方法中使用缩放变换(OnPaint() - 请参阅MSDN)绘制一条线时,我看到了奇怪的行为。

当对ScaleTransform方法使用大的y比例因子时,如果x比例设置在1x以上,则该线突然变得更大。

将绘制线条的笔的宽度设置为-1似乎可以解决问题,但我不想绘制非常细的线条(该线条必须稍后打印,1px太薄)。< / p>

以下是一些示例代码来说明问题:

public class GraphicsTestForm : Form
{
    private readonly float _lineLength = 300;
    private readonly Pen _whitePen;

    private Label _debugLabel;

    public GraphicsTestForm()
    {
        ClientSize = new Size(300, 300);

        Text = @"GraphicsTest";
        SetStyle(ControlStyles.ResizeRedraw, true);

        _debugLabel = new Label
        {
            ForeColor = Color.Yellow,
            BackColor = Color.Transparent
        };
        Controls.Add(_debugLabel);

        _lineLength = ClientSize.Width;
        _whitePen = new Pen(Color.White, 1f); // can change pen width to -1
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        float scaleX = ClientSize.Width / _lineLength;
        const int ScaleY = 100;

        e.Graphics.Clear(Color.Black);

        _debugLabel.Text = @"x-scale: " + scaleX;

        // scale the X-axis so the line exactly fits the graphics area
        // scale the Y-axis by scale factor
        e.Graphics.ScaleTransform(scaleX, ScaleY);

        float y = ClientSize.Height / (ScaleY * 2f);
        e.Graphics.DrawLine(_whitePen, 0, y, _lineLength, y);

        e.Graphics.ResetTransform();
    }
}

我希望线条/笔能够优雅地缩放,而不会如此大幅度地跳跃。

(另外,我注意到,当线条非常大时,不会在多个显示器上连续绘制。也许这是相关的?)

2 个答案:

答案 0 :(得分:3)

尝试根据比例更改笔的宽度:

 _whitePen = new Pen(Color.White, 1f / ScaleY); 
 e.Graphics.DrawLine(_whitePen, 0, y, _lineLength, y); 

答案 1 :(得分:1)

我刚刚补偿了笔线几何中的整体缩放; -

m_Pen->SetWidth(1.0f);
m_Pen->ScaleTransform(1.0f / ZoomX, 1.0f / ZoomY);