0

I am currently working on my first WPF project to make cards for a card game and save them into a folder as a PNG. Right now I am using the method explained in this other answer I found. Here is the code I'm using:

private void saveCard()
    {
        Rect bounds = VisualTreeHelper.GetDescendantBounds(cardArea);
        double dpi = 96d;


        RenderTargetBitmap rtb = new RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, dpi, dpi, System.Windows.Media.PixelFormats.Default);


        DrawingVisual dv = new DrawingVisual();
        using (DrawingContext dc = dv.RenderOpen())
        {
            VisualBrush vb = new VisualBrush(cardArea);
            dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
        }

        rtb.Render(dv);

        BitmapEncoder pngEncoder = new PngBitmapEncoder();
        pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

        try
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            pngEncoder.Save(ms);
            ms.Close();

            System.IO.File.WriteAllBytes(System.AppDomain.CurrentDomain.BaseDirectory + "/Heroes/" + HeroName.Content + ".png", ms.ToArray());
        }
        catch (Exception err)
        {
            MessageBox.Show(err.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

It works fine, but I noticed that the saved pictures look "pixelated". This is especially noticeable when compared to the one in the canvas, or even a screenshot. Here is an example.

I checked the resolution of both and they had the same dimensions. What am I doing wrong? Is there anything I can do to fix it? Should I save the picture under another file type?

Please let me know.

  • As a note, instead of saving the encoded frame to a MemoryStream and subsequently calling File.WriteAllBytes, you may as well directly save it to a FileStream. – Clemens Nov 10 '17 at 09:18
  • In the image you linked the image on the left uses standard antialiasing and the one on the right uses sub pixel antialiasing (AKA true type) see https://stackoverflow.com/a/40074278/3877726 for an explanation and code (javascript which is easily to convert to C#) on how to create sub pixel antialiasing. – Blindman67 Nov 10 '17 at 13:13

0 Answers0