Graphics.MeasureString不包含某些字符的某些部分

时间:2020-09-03 09:05:21

标签: c# gdi+ text-rendering

我正在使用此方法从字符串生成位图:

private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize,
    FontStyle fontStyle = FontStyle.Regular, StringFormat stringFormat = default,
    float MaxWidth = float.MaxValue, float MaxHeight = float.MaxValue, float xDpi = 72, float yDpi = 72,
    Color backgroundColor = default, Color foregroundColor = default)
{
    if (text == "") return null;
    Bitmap bitmap = new Bitmap(1, 1);
    Graphics graphics = Graphics.FromImage(bitmap);
    if (stringFormat == default) stringFormat = new StringFormat();
    if (backgroundColor == default) backgroundColor = Color.Transparent;
    if (foregroundColor == default) foregroundColor = Color.Black;

    Font font = new Font(fontFamily, fontSize, fontStyle);

    SizeF stringSize = graphics.MeasureString(text, font, int.MaxValue, stringFormat);
    while (stringSize.Width > MaxWidth || stringSize.Height > MaxHeight)
    {
        fontSize -= (float)0.1;
        font = new Font(fontFamily, fontSize, fontStyle);
        stringSize = graphics.MeasureString(text, font, int.MaxValue, stringFormat);
    }

    bitmap = new Bitmap((int)stringSize.Width, (int)stringSize.Height);
    graphics = Graphics.FromImage(bitmap);
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

    bitmap.SetResolution(xDpi,yDpi);
    graphics.Clear(backgroundColor);
    
    int x = 0;
    if (stringFormat.FormatFlags == StringFormatFlags.DirectionRightToLeft && stringFormat.Alignment == StringAlignment.Center)
        x = (int)stringSize.Width / 2;
    else if (stringFormat.FormatFlags == StringFormatFlags.DirectionRightToLeft) x = (int)stringSize.Width;
    else if (stringFormat.Alignment == StringAlignment.Center) x += (int)stringSize.Width / 2;

    graphics.DrawString(text, font, new SolidBrush(foregroundColor), x, 0, stringFormat);

    return bitmap;
}

它可以正常工作,但是使用IranNastaliq字体时有时不生成某些字符。例如,查看在字符串开头的波斯字符“گ”(突出显示的部分在原始图片中,而不是由GDI创建)。带圆圈的部分应该更长:
enter image description here
和这个。裁剪圆点(也在字符串的开头):
enter image description here
我认为Graphics.MeasureString不能衡量这些部分。我可以在开始时添加一些空格字符,但这会导致其他一些问题。我该如何解决?

0 个答案:

没有答案