2012-05-07 26 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);