Sjors Miltenburg
Sjors Miltenburg

Reputation: 2740

Canvas line strokethickness with double value creates moire effect

I am trying to draw a waveform. I have a precalculated amount of datapoints I want to draw (for instance 1000). I want to fill the full width of my canvas control with the waveform. Therefore I have to recalculate the width of every datapoint that I draw.

To do this I tried to set the StrokeThickness to the total width divided by the nr of datapoints. (so for instance 0.35629) and print a line of 0.35629 pixels wide every 0.35629 pixels.

This creates an unwanted moire effect.

To me it feels weird that the StrokeThickness is a double, because how will WPF draw a line of 0.35629 pixels wide?

Below a code example to show what I mean. The first half is ok, the second half has the moire effect.

Is this the way to go or do I need another approach?

for (int i = 0; i < 500; i++)
{
    Line line = new Line();
    line.X1 = i;
    line.X2 = i;
    line.Y1 = 0;
    line.Y2 = 100;
    line.Stroke = new SolidColorBrush(Colors.Black);
    line.StrokeThickness = 1;
    this.demoCanvas.Children.Add(line);
}

const double canvasWidth = 525;
const double nrOfDatapoints = 500d;
const double pixelsPerPoint = canvasWidth/nrOfDatapoints  ;
double x = 500;
for (int i = 0; i < nrOfDatapoints; i++)
{
    Line line = new Line();
    line.X1 = x;
    line.X2 = x;
    line.Y1 = 0;
    line.Y2 = 100;
    line.Stroke = new SolidColorBrush(Colors.Black);
    line.StrokeThickness = pixelsPerPoint;
    this.demoCanvas.Children.Add(line);
    x += pixelsPerPoint;
}

Upvotes: 1

Views: 1430

Answers (1)

Sergei B.
Sergei B.

Reputation: 3227

To avoid moire you should set SnapToDevicePixels="True". Check it out here

Upvotes: 4

Related Questions