简体   繁体   English

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

[英]Incorrect scaling of Pen when using Graphics.ScaleTransform

I'm seeing strange behaviour when drawing a line with a scale transform ( Graphics.ScaleTransform() - see MSDN ) in my OnPaint() method. 在我的OnPaint()方法中使用缩放变换( Graphics.ScaleTransform() - 参见MSDN )绘制一条线时,我看到了奇怪的行为。

When using a large y-scale factor for the ScaleTransform method, then if the x-scale is set above 1x, the line suddenly becomes much larger. 当为ScaleTransform方法使用大的y比例因子时,如果x-scale设置在1x以上,则该线突然变得更大。

Setting the width of pen with which the line is drawn to -1 seems to get round the problem, but I do not want to draw a very thin line (the line must be printed later, 1px is too thin). 将绘制线条的笔的宽度设置为-1似乎可以解决问题,但我不想绘制非常细的线条(线条必须稍后打印,1px太薄)。

Here's some sample code to demonstrate the problem: 以下是一些示例代码来演示此问题:

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();
    }
}

I would like the line/pen to scale gracefully, without jumping in size so dramatically. 我希望线/笔能够优雅地扩展,而不会如此大幅度地跳跃。

(Additionally, I noticed that when the line is very large, it is not drawn continuously across multiple monitors. Perhaps this is related?) (另外,我注意到当线条非常大时,不会在多个监视器上连续绘制。也许这是相关的?)

Try to change the pen width according to the scale: 尝试根据比例更改笔宽:

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

I just compensated for the overall scaling in the pens line geometry;- 我只是补偿了笔线几何中的整体缩放; -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM