ImageSharp -- How do I draw a text to the top of the image? #87
-
If I create a font, e.g.
creates this image: and there is a big gap on the top. I use ImageSharp 1.0.1 and ImageSharp.Drawing 1.0.0-beta0010 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I think this is a bug, I've filed one at #88 |
Beta Was this translation helpful? Give feedback.
-
Text has a line high and you are drawing the line at the top not the characters, the reason for this is that different characters within the same font can have wildly different heights and we needs a consistent baseline for rendering. There was a stack overflow question with a similar issue here https://stackoverflow.com/a/53023454/234855 but the solution was basically this: /// <param name="text">one or more characters to scale to fill as much of the target image size as required.</param>
/// <param name="targetSize">the size in pixels to generate the image</param>
/// <param name="outputFileName">path/filename where to save the image to</param>
private static void GenerateImage(string text, string outputFileName)
{
FontFamily fam = SystemFonts.Find("Arial");
Font font = new Font(fam, 100);
RendererOptions style = new RendererOptions(font, 72);
// this is the important line, where we render the glyphs to a vector instead of directly to the image
// this allows further vector manipulation (scaling, translating) etc without expensive pixel operations.
IPathCollection glyphs = SixLabors.Shapes.TextBuilder.GenerateGlyphs(text, style);
// move the vectorised glyph so that it touchs top and left edges
// could be tweeked to center horizontaly & vertically here
glyphs = glyphs.Translate(-glyphs.Bounds.Location);
using (Image<Rgba32> img = new Image<Rgba32>(targetSize.Width, targetSize.Height))
{
img.Mutate(i => i.Fill(new GraphicsOptions(true), Rgba32.Black, glyphs)); // not we are using the vector based fill APIs over the text base draw ones
img.Save(outputFileName);
}
} |
Beta Was this translation helpful? Give feedback.
Text has a line high and you are drawing the line at the top not the characters, the reason for this is that different characters within the same font can have wildly different heights and we needs a consistent baseline for rendering.
There was a stack overflow question with a similar issue here https://stackoverflow.com/a/53023454/234855 but the solution was basically this: