Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - WritablebitmapEx render a smooth line

I need to render a "smooth" line using a WritableBitmap' i'm using WritableBitmapExtenstions.

Every 12 ms i get 12 points consisting of an (X,Y) where the Y is normalized to the center of the screen, and the X represents a pixel on the the image surface (Bitmap) .

Init :

 _wb =  new WriteableBitmap((int)mainGrid.ActualWidth, (int)mainGrid.ActualHeight, 96.0, 96.0, PixelFormats.Pbgra32, null);
 image.Source = _wb;

 CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

CompositionTarget_Rendering :

   Point [] points = null;
   if (blocks.TryDequeue(out points)) // blocks is a ConcurrentQueue which gets enqueued on a timer interval on another thread.
   {
       using (_wb.GetBitmapContext())
       {                    
           Draw(points);
       }
   }

Draw :

   private void Draw(Point[] points)
   {
        int x1, y1, x2, y2;

        if (lastX != 0 && lastY != 0)
        { // Draw connection to last line segment.
            x1 = lastX;
            y1 = lastY;
            x2 = (int)points[0].X;
            y2 = (int)points[0].Y;

            _wb.DrawLine(x1, y1, x2, y2, Colors.Red);
        }

        for (int i = 0; i < points.Count() - 1; i++)
        {// draw lines. [0],[0] - [1],[1]  ; [1],[1] - [2],[2]   .....and so on.
            x1 = (int)points[i].X;
            y1 = (int)points[i].Y;
            x2 = (int)points[i + 1].X;
            y2 = (int)points[i + 1].Y;

            _wb.DrawLine(x1, y1, x2, y2, Colors.Red);
        }

        lastX = (int)points[points.Count() - 1].X;
        lastY = (int)points[points.Count() - 1].Y;      
   }  

The result :

enter image description here

Well the lines are exactly in place , but the way it was drawn was not smooth even tough i used a Writablebitmap and drew all the lines on the Rendering event , each segment was still rendered as a batch.

so to conclude should i draw one pixel at a time in order to make this smooth ? if you look as the WritablebitmapEx Curve sample the project named "WriteableBitmapExCurveSample.Wpf" (This will require you to download the samples from the link above)

you can see the kind of smoothness i wan't to achieve .

like image 746
eran otzap Avatar asked Apr 26 '26 07:04

eran otzap


2 Answers

Try using the DrawLineAa (Aa == Antialiased) extension method instead of DrawLine.

like image 180
Monroe Thomas Avatar answered Apr 27 '26 21:04

Monroe Thomas


For the most proper result, you could apply a post-fx matrix filter. http://lodev.org/cgtutor/filtering.html

I don't remember well how to implement this with asp.net but i think there is something similar in CompositionTarget.

like image 27
Antoine C. Avatar answered Apr 27 '26 21:04

Antoine C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!