1
votes

I am currently writing a .NET Core App to run cross-platform. Part of this is App is Drawing a Text and overlay onto a Bitmap.

So I added System.Drawing.Common and finally ended up with a working Code(On Windows) like this:

    public static Bitmap WriteText(Bitmap bmp, string txt)
    {
        RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

        // Create graphic object that will draw onto the bitmap
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            StringFormat format = new StringFormat()
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            // dampening
            using (Brush brush = new SolidBrush(Color.FromArgb(69, Color.Black)))
                g.FillRectangle(brush, rectf);

            var fSize = 26;
            var fFam = Fonts.GetDefaultFontName();
            // Draw the path
            GraphicsPath p = new GraphicsPath();
            p.AddString(txt, fFam, (int)FontStyle.Regular, g.DpiX * fSize / 72.2f, rectf, format);
            g.DrawPath(new Pen(Color.FromArgb(180, Color.Black), 8), p);
            // Draw the text
            g.DrawString(txt, new Font(fFam, fSize), Brushes.White, rectf, format);
            // Flush all graphics changes to the bitmap
            g.Flush();
        }
        // Now save or use the bitmap
        return bmp;
    }

On Windows Outputs are generated correctly or as expected like this for Example:

Test A

But when run on my Ubuntu/linux server, the GraphicsPath/Shadow would generate like this:

Test B

My first thought was an Error in the DPI-calculation since my Server doesn't have an X-Server installed but apparently the GraphicsPath is drawn correct; just the position is wrong?

*Editnote: Also the "Formatting" apparently works on the usual DrawString... so thats extra weird

Maybe I've missed something but this looks like a platform-specific bug to me?

I'd appreciate any help & opinions at this point... Thanks

I've run across a similar issue, where GraphicsPath.AddString only shows the first 15 characters or so of the string and then just gives up. Our solution is to migrate to a different 2D graphics library, probably SkiaSharp. System.Drawing.Common is a bit of a hack that no-one really wanted to write or maintain, so I'm resigned to it not getting better (and having looked at the underlying code, it looks like a bit of a nightmare to fix properly even if you did want to DIY). - Rook