DrawString - 某些字体中不需要的垂直偏移量

时间:2015-08-09 14:35:53

标签: c# graphics fonts

我在图形对象上绘制一些文本。对于某些字体,绘制的文本有一些不需要的垂直偏移。

以下是代码:

Bitmap img = new Bitmap(Width, Height);
Graphics GraphicObject = Graphics.FromImage(img);
GraphicObject.TextRenderingHint = TextRenderingHint.AntiAlias;
GraphicObject.DrawRectangle(Pens.Red, X, Y, Width, Height);
StringFormat format = new StringFormat();
format.FormatFlags = StringFormatFlags.NoClip;

GraphicObject.DrawString(
     "SampleText",
     new FontFamily("Font_Name"),
     Color.White,
     new RectangleF(X, Y, Width, Height),
     format
);

结果如下: enter image description here

如您所见,两种字体的位置错误

我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

经过一番努力,我解决了一个小问题。

首先,我在空Graphics个对象上绘制文字。然后我会在y轴上扫描第一个文本像素。这一点是字体的y偏移量。然后,我将在Graphics

y - yOffset对象中绘制文字
Bitmap img = new Bitmap(Width, Height);
Graphics GraphicObject = Graphics.FromImage(img);
GraphicObject.TextRenderingHint = TextRenderingHint.AntiAlias;
GraphicObject.DrawRectangle(Pens.Red, X, Y, layer.Width, layer.Height);
StringFormat format = new StringFormat();
format.FormatFlags = StringFormatFlags.NoClip;

int yOffset = GetYOffset(layer.Width,layer.Height,TextFont,layer.Text, format);

GraphicObject.DrawString(
     "SampleText",
     new FontFamily("Font_Name"),
     Color.White,
     new RectangleF(X, Y - yOffset, layer.Width, layer.Height),
     format
);

...

private int GetYOffset(int Width, int Height, System.Drawing.Font TextFont, string Text, StringFormat format)
{
    Bitmap img = new Bitmap(1000, 1000);
    Graphics testGaraphic = null;
    testGaraphic = Graphics.FromImage(img);

    testGaraphic.FillRectangle(Brushes.White, 0, 0, Width, Height);
    testGaraphic.DrawString(Text, TextFont, Brushes.Black, 0, 0, format);
    for (int y = 0; y < Height; y++)
        for (int x = 0; x < Width; x++)
            if (img.GetPixel(x, y).Name != "ffffffff")
                return y;
    return 0;
}

结果: enter image description here

答案 1 :(得分:0)

Ali Gonabadi的上述解决方案挽救了我的生命。我进行了一些修改,以便在使用抗锯齿文本时更加精确。下面是我用来获取X偏移坐标的函数,并对其进行了一些修改,这些修改与位图的大小和SmoothingMode有关:

private int GetXOffset(int Width, int Height, System.Drawing.Font TextFont, string Text, StringFormat format)
{
    Bitmap image = new Bitmap(Width, Height);
    Graphics g = Graphics.FromImage(image);

    g.SmoothingMode = SmoothingMode.AntiAlias;

    g.FillRectangle(Brushes.Black, 0, 0, Width, Height);
    g.DrawString(Text, TextFont, Brushes.White, 0, 0, format);
    for (int x = 0; x < Width; x++)
        for (int y = 0; y < Height; y++)
            if (image.GetPixel(x, y).Name != "ff000000")
                return x;
    return 0;
}