How to make drawLine smoother?
Asked Answered
C

3

6

I use the following code to draw line:

Graphics g = this.CreateGraphics();
Pen p = new Pen(Color.Black,3);
g.DrawLine(p,...);
// ...

Why the straight line is zigzag kind of, not straight and smooth at all. How could I make it straight and smoother?

Centralia answered 6/4, 2011 at 15:46 Comment(1)
Zig-zag? That makes me think you're not just talking about something that a little bit of anti-aliasing can fix. Can you post a screenshot?Alp
S
11

You need to enable anti-aliasing. Set Graphics.SmoothingMode to AntiAlias as described here: http://msdn.microsoft.com/en-us/library/system.drawing.graphics.smoothingmode.aspx

Subtrahend answered 6/4, 2011 at 15:47 Comment(0)
S
9

Override the OnPaint() method of your form or implement the Paint event of a control. Use the passed e.Graphics object to draw. It will be properly initialized to draw anti-aliased lines. And can be double-buffered so it doesn't flicker. Call Invalidate() to force a repaint.

Using Control.CreateGraphics() is wrong in 99.9% of all cases. Whatever you draw cannot persist. It will be gone when you minimize and restore the window. Or when you partly move it off the screen and back. Or when you overlap another window on yours on XP and any machine that doesn't have Aero enabled. CreateGraphics() is only suitable for animations at frame rates larger than ~20 fps.

Southport answered 6/4, 2011 at 16:28 Comment(2)
Yes! This is the reason at first I cannot see any of my line. I add one more event handler to Paint. I tried to pass the e.Graphics but it gives an error "invalid parameter".Centralia
@spspli: You don't pass e.Graphics to anything. You simply call its DrawLine function: e.Graphics.DrawLine(p, ...)Alp
C
-1

Perfect match with our need.

Gift 4 u:

Graphics g = e.Graphics;
    
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

Picture of the result with AntiAlias

Callous answered 7/4, 2024 at 13:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.