c# - 使用 Graphics.ScaleTransform 时 Pen 的缩放比例不正确

标签 c# winforms graphics scaletransform

在我的 OnPaint() 方法中绘制带有比例变换(Graphics.ScaleTransform() - 参见 MSDN )的线条时,我看到了奇怪的行为。

当对 ScaleTransform 方法使用较大的 y 比例因子时,如果将 x 比例设置为高于 1x,线条会突然变得更大。

将画线的笔宽设置为-1似乎可以解决这个问题,但我不想画很细的线(线必须稍后打印,1px太细了)。

下面是一些演示问题的示例代码:

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

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

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

最佳答案

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

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

关于c# - 使用 Graphics.ScaleTransform 时 Pen 的缩放比例不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10482032/

相关文章:

.net - Windows 窗体 : Using a user control like a container control

java - Java中除空格外的屏幕填充

c# - 如何轻松地重新排序 TabControl?

c# - 在 WPF 中调整网格内的 Canvas

c# - 为什么只允许UI线程修改UI?

c# - 你能在 C# 中获取堆栈上的变量列表吗?

c# - 如何在 C#/Winforms 中将队列绑定(bind)到 DataGridView?

java - 在android java中转换图像格式

java - 如何将 BufferedImage 数据直接传递给 OpenCL?

c# - 使用电子表格设备保护 Excel 工作表,同时保持自动筛选