Question

I need to draw a string with Graphics class with DrawString method. But image has some black pixels, not the exact color. How can I draw it clearly?

Sample string

 public Image Ciz()
    {
        Color renk = Color.FromArgb(255, 133, 199);
        Bitmap result = new Bitmap(KutuBoyutu.Genislik, KutuBoyutu.Yukseklik);
        result.SetResolution(100, 100);
        Graphics g = Graphics.FromImage(result);
        g.SmoothingMode = SmoothingMode.HighQuality;
        Brush drawBrush = new SolidBrush(renk);
        StringFormat stringFormat = new StringFormat();
        stringFormat.Alignment = StringAlignment.Center;
        stringFormat.LineAlignment = StringAlignment.Center;
        Rectangle rect1 = new Rectangle(0, 0, result.Width, result.Height);
        Font font = new Font("Arial", 15f, FontStyle.Bold, GraphicsUnit.Pixel);
        g.DrawString(Yazi, font, drawBrush, rect1, stringFormat);
        drawBrush.Dispose();
        return result;
    }
Was it helpful?

Solution 2

Add

g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

to your code.

TextRenderingHint.AntiAliasGridFit works as well.

OTHER TIPS

Drawing text requires a well-defined background so that the anti-aliasing effect can work properly. You don't have any, you forgot to initialize the bitmap. Which left its pixels at the default, black with an alpha of 0.

So the text renderer will try to alias the letter to blend into a black background. You see that, those almost-black pixels now become very visible against a white background. It will only look good if you draw the bitmap on top of a black background. Fix:

using (Graphics g = Graphics.FromImage(result)) {
    g.Clear(Color.White);
    // etc...
}

If you cannot fix the background color then you need to give up on anti-aliasing. Set the TextRenderingHint to SingleBitPerPixelGridFit. You won't like it much :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top