Skip to content

Commit

Permalink
fix: width in TextMetrics when text is ending with spaces
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed May 30, 2022
1 parent 1f73a77 commit 5961fd2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
11 changes: 11 additions & 0 deletions __test__/text.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,14 @@ test(`strokeText-line-break-as-space`, async (t) => {
ctx.strokeText('Hello\nCanvas', x, 200)
await snapshotImage(t)
})

test(`measureText with suffix spaces`, async (t) => {
const { ctx } = t.context
ctx.font = '50px Iosevka Slab'
const { width } = ctx.measureText('Hello')
const { width: widthWithSpace } = ctx.measureText('hello ')
const { width: widthWithTwoSpace } = ctx.measureText('hello ')
t.not(width, widthWithSpace)
t.is(ctx.measureText(' ').width, widthWithSpace - width)
t.is(ctx.measureText(' ').width, widthWithTwoSpace - width)
})
11 changes: 5 additions & 6 deletions skia-c/skia_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -376,14 +376,10 @@ extern "C"
text_style.setForegroundColor(*PAINT_CAST);
text_style.setTextBaseline(TextBaseline::kAlphabetic);

SkFontMetrics font_metrics;
text_style.getFontMetrics(&font_metrics);

ParagraphStyle paragraph_style;
paragraph_style.turnHintingOff();
paragraph_style.setTextStyle(text_style);
paragraph_style.setTextDirection(text_direction);
ParagraphBuilderImpl builder(paragraph_style, font_collection);
ParagraphBuilderImpl builder(paragraph_style, font_collection, SkUnicode::Make());
builder.addText(text, text_len);
auto paragraph = static_cast<ParagraphImpl *>(builder.Build().release());
paragraph->layout(MAX_LAYOUT_WIDTH);
Expand All @@ -395,6 +391,8 @@ extern "C"
auto glyphs = run.glyphs();
auto font = run.font();
auto glyphs_size = glyphs.size();
SkFontMetrics font_metrics;
font.getMetrics(&font_metrics);
SkRect bounds[glyphs_size];
font.getBounds(glyphs.data(), glyphs_size, &bounds[0], nullptr);
auto first_char_bounds = bounds[0];
Expand All @@ -416,7 +414,8 @@ extern "C"
ascent = char_top;
}
}
auto line_width = line_metrics.fWidth;
// line_metrics.fWidth doesn't contain the suffix spaces
auto line_width = run.calculateWidth(0, glyphs_size, false);
auto alphabetic_baseline = paragraph->getAlphabeticBaseline();
auto css_baseline = (CssBaseline)baseline;
SkScalar baseline_offset = 0;
Expand Down

0 comments on commit 5961fd2

Please sign in to comment.