在我的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();
}
}
我想行/筆輕鬆擴充,沒有大小跳那麼厲害。
(此外,我注意到,當行是非常大的,它不是不斷跨越多個顯示器繪製也許這是有關?)
問GDI +做的不尋常的事情從來都不是沒有問題的。不尋常的意思是用不同的角度來繪製厚度。保持X和Y比例因子相同以獲得更好的結果。 –
@HansPassant感謝您的提示!實際上我需要繪製一條正弦曲線,其中X軸上的點數爲100,而Y軸僅在-1和1之間。因此,X和Y比例因子的差異。我應該在繪製之前單獨縮放這些點並忘記圖形變換嗎? –