2012-05-07 24 views
0

在我的OnPaint()方法中使用缩放比例(Graphics.ScaleTransform() - 请参见MSDN)画线时出现奇怪行为。使用Graphics.ScaleTransform时笔的缩放比例不正确

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

我想行/笔轻松扩充,没有大小跳那么厉害。

(此外,我注意到,当行是非常大的,它不是不断跨越多个显示器绘制也许这是有关?)

+1

问GDI +做的不寻常的事情从来都不是没有问题的。不寻常的意思是用不同的角度来绘制厚度。保持X和Y比例因子相同以获得更好的结果。 –

+0

@HansPassant感谢您的提示!实际上我需要绘制一条正弦曲线,其中X轴上的点数为100,而Y轴仅在-1和1之间。因此,X和Y比例因子的差异。我应该在绘制之前单独缩放这些点并忘记图形变换吗? –

回答

2

尝试根据规模,更改笔宽:

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

连续创建Pen对象有什么问题吗? –

+0

这种工作方式:但是,这条线仍然不能平稳地放大和缩小 - 例如,如果我想要一个更粗的线(我使用10f/ScaleY),但这会带来问题。 –

+0

关于连续创建,处理它们很方便。看看[这个前面的问题](http://stackoverflow.com/questions/1819096/is-it-important-to-dispose-solidbrush-and-pen)但是,为了避免不必要的性能下降,你可以验证前一支笔是否与您现在需要的笔相同(保存最后一个刻度值)。 – 2012-05-08 06:31:55

1

我只是补偿的笔线几何总体比例; -

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