在我的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比例因子的差异。我应该在绘制之前单独缩放这些点并忘记图形变换吗? –