I’m rendering tickets for printing using SkiaSharp. I print multiple lines in a regular font size, and the ticket number using a large font. Here are the SKPaint objects I’m using:
using SKPaint regular = new()
{
Color = SKColors.Black,
IsAntialias = true,
TextSize = regularFontSize, // 30
Typeface = SKTypeface.FromFamilyName(
familyName: "Roboto")
};
using SKPaint large = new()
{
Color = SKColors.Black,
IsAntialias = true,
TextSize = largeFontSize, // 250
Typeface = SKTypeface.FromFamilyName(
familyName: "Roboto")
};
I draw the text like this:
canvas.DrawText(Model.TicketNumber, X, Y, large);
canvas.DrawText(Model.LocationInfo, X, Y, regular);
I’m centering the text horizontally in the image the following way:
I measure the text size (according to this guide https://swharden.com/csdv/skiasharp/text/)
large.MeasureText(Model.TicketNumber, ref rectangle);
And then I calculate the X coordinate thusly:
X = canvasSize/2 - rectangle.size/2
I get an output that looks like this:
I’ve added the lines in Paint. The orange vertical line is the center line. You can see immediately that the large text “888” is noticeably off-center. Measuring the actual pixels shows that while the other lines are either dead center, or just off by 5 or fewer pixels, the big numbers are indeed quite off.
I have tried substituting letters instead of numbers, the resulting text was still just as off-center. The calculation logic is the same for all the lines. The only variable is the font size. Before you ask, I’m certain I don’t have any leading white spaces in the string.
I have debugged the code and looked at the measured text dimensions. The width was the same as the width of the printed text. I also checked the calculated X value. It was 102.6 pixels (plus change). Incidentally, if the text had started at that X coordinate, it would have been dead center.
It’s like the text renderer is a bit off when placing the text, and this discrepancy increases with the font size. Any idea how to fix this? Funnily enough, the Y coordinate is always spot on.
Alternatively, is there another way to center text horizontally on the canvas? One that doesn’t have this problem?
Thank you.