Question

I have a problem measuring text using skia measureText() function. The value returned is inaccurate.

SkPaint *skPaint = new SkPaint();

SkTypeface* myFont = SkTypeface::CreateFromName("Impact", SkTypeface::kNormal);

skPaint->setTypeface(myFont);
skPaint->setAntiAlias(true);
skPaint->setTextAlign(SkPaint::kLeft_Align);
skPaint->setTextEncoding(SkPaint::kUTF16_TextEncoding);
skPaint->setTextSize(SkIntToScalar(120));
skPaint->setColor(0xff000001);
canvas->drawText(text, length,  SkIntToScalar(x) ,  SkIntToScalar(y) , *skPaint);
SkScalar width = skPaint->measureText(text, length);

The width returned by measureText() is 451.

I checked the generated bitmap text via a photo editor app, the actual width is only 438.

Any thoughts on getting the accurate width of text in SKIA?

Thank you!

Was it helpful?

Solution

I believe what you are trying to match will come from "bounds"

SkRect bounds;
SkScalar textWidth = paint.measureText("some", 4, &bounds);

which is a minimum rectangle to fit a given text, whereas textWidth is slightly larger than that.

OTHER TIPS

I faced this issue too. Dont know why exactly it happens, maybe because of kerning differences, but i came to this:

SizeF RenderTextAndroid::GetStringSizeF() {
    UpdateFont();
    const base::string16& text = GetLayoutText();
    std::vector<SkScalar> widths(text.length());
    paint_.getTextWidths(text.c_str(), GetStrByteLen(text), &widths[0], NULL);
    return SizeF(std::accumulate(widths.begin(), widths.end(), 0),
        font_metrics_.fBottom - font_metrics_.fTop);
}

Where UpdateFont just sets new parameters to SkPaint

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top