1

I need to draw a RTF text on a custom background. I am using an extended RichTextBox control as described for example here to render RTF itself. This works fine if the graphics is associated with the screen. But when I use graphics created from a bitmap the cleartype fonts have ugly black fragments like the antialiasing does not blend the text with the background correctly (I draw the background first). What is the reason of this? And can it be somehow fixed?

Example of code producing an ugly bitmap:

private void CreateBitmap(string rtf, Rectangle bitmapRectangle)
{
    using (Bitmap bitmap = new Bitmap(bitmapRectangle.Width, bitmapRectangle.Height))
    {
        using (Graphics gr = Graphics.FromImage(bitmap))
        {
            gr.Clear(Color.Yellow);

            // extended RichTextBox control from www.andrewvos.com
            RichTextBoxDrawer rtbDrawer = new RichTextBoxDrawer();
            rtbDrawer.Rtf = rtf;
            rtbDrawer.Draw(gr, bitmapRectangle);

            bitmap.Save(@"c:\bitmap.png");
        }
    }
}

One more thing: Graphics.DrawString works fine and draws correctly anti-aliased text.

4

1 に答える 1

1

わかりました、間違った場所に背景を描いていたようです。RichTextBoxDrawer.Draw メソッドで送信された EM_FORMATRANGE メッセージであるデバイス コンテキスト ハンドルから作成されたグラフィックに背景を描画すると、テキストが正しくレンダリングされます。

public void Draw(Graphics graphics, Rectangle layoutArea, Bitmap background = null)
{
    //Calculate the area to render.
    SafeNativeMethods.RECT rectLayoutArea;
    rectLayoutArea.Top = (int)(layoutArea.Top * anInch);
    rectLayoutArea.Bottom = (int)(layoutArea.Bottom * anInch);
    rectLayoutArea.Left = (int)(layoutArea.Left * anInch);
    rectLayoutArea.Right = (int)(layoutArea.Right * anInch);    

    IntPtr hdc = graphics.GetHdc();
    using (Graphics backgroundGraphics = Graphics.FromHdc(hdc))
    {
        // draw some background
        backgroundGraphics.Clear(Color.Yellow);
    }

    // rest of the method is same
}
于 2012-11-22T13:04:05.447 に答える