使用g.DrawString()用不同颜色的字符串写一个单词

时间:2014-09-18 23:18:26

标签: c# graphics drawstring

我使用下面的函数在图像上绘制一个字符串。当我使用一种颜色绘制字符串时,它大部分都很好用。

但是我想要一个不同颜色的词。例如,我想绘制"这是TEST",我希望TEST为红色。

使用这种方法可以做到这一点?

        System.Drawing.Image newImg = new System.Drawing.Bitmap(500, 500);
        pictureBox1.Image = TextOverlay(newImg, "This is a TEST", this.Font, Color.Black, ContentAlignment.MiddleCenter, 0.6F);

我指的是这行代码而不是OverlayColor参数:

        g.DrawString(OverlayText, f, b, rect, strFormat);

这是完整的功能:

    public static Bitmap TextOverlay(Image img, string OverlayText, Font OverlayFont, Color OverlayColor, System.Drawing.ContentAlignment Position, float PercentFill)
    {
        // create bitmap and graphics used for drawing
        // "clone" image but use 24RGB format
        Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmp);
        g.DrawImage(img, 0, 0);

        int alpha = 255;

        // Create the brush based on the color and alpha
        SolidBrush b = new SolidBrush(Color.FromArgb(alpha, OverlayColor));

        // Measure the text to render (unscaled, unwrapped)
        StringFormat strFormat = StringFormat.GenericTypographic;
        SizeF s = g.MeasureString(OverlayText, OverlayFont, 100000, strFormat);

        // Enlarge font to specified fill (estimated by AREA)
        float zoom = (float)(Math.Sqrt(((double)(img.Width * img.Height) * PercentFill) / (double)(s.Width * s.Height)));
        FontStyle sty = OverlayFont.Style;
        Font f = new Font(OverlayFont.FontFamily, ((float)OverlayFont.Size) * zoom, sty);

        int charFit;
        int linesFit;
        float SQRTFill = (float)(Math.Sqrt(PercentFill));
        strFormat.FormatFlags = StringFormatFlags.NoClip; //|| StringFormatFlags.LineLimit || StringFormatFlags.MeasureTrailingSpaces;
        strFormat.Trimming = StringTrimming.Word;
        SizeF layout = new SizeF(((float)img.Width) * SQRTFill, ((float)img.Height) * 1.5F); // fit to width, allow height to go over
        s = g.MeasureString(OverlayText, f, layout, strFormat, out charFit, out linesFit);

        // Determine draw area based on placement
        RectangleF rect = new RectangleF((bmp.Width - s.Width) / 2F,
                    (bmp.Height - s.Height) / 2F,
                    layout.Width,
                    ((float)img.Height) * SQRTFill);

        // Add rendering hint (thx to Thomas)
        g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

        // finally, draw centered text!
        g.DrawString(OverlayText, f, b, rect, strFormat);

        // clean-up
        g.Dispose();
        b.Dispose();
        f.Dispose();

        return bmp;
    }

0 个答案:

没有答案