Skip to content

Commit 1b3132c

Browse files
committed
Calculate width for multiline text
1 parent 571ce7b commit 1b3132c

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

ext/fast_excel/text_width_ext.c

+8-1
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,7 @@ static VALUE
405405
rb_some_text_width(VALUE text, float default_width, float char_widths[127], float kernings[127][127]) {
406406
char *text_value = StringValueCStr(text);
407407

408+
double max = 0;
408409
double total = 0;
409410
char ch = 0;
410411
char nch = 0;
@@ -414,6 +415,11 @@ rb_some_text_width(VALUE text, float default_width, float char_widths[127], floa
414415
ch = text_value[i];
415416
nch = text_value[i + 1];
416417

418+
if (ch == 10) {
419+
if (total > max) max = total;
420+
total = 0;
421+
}
422+
417423
if (ch < 32) continue;
418424

419425
if (ch > 126) {
@@ -425,8 +431,9 @@ rb_some_text_width(VALUE text, float default_width, float char_widths[127], floa
425431
total += char_widths[ch];
426432
}
427433
}
434+
if (total > max) max = total;
428435

429-
return DBL2NUM(total);
436+
return DBL2NUM(max);
430437
}
431438

432439
static VALUE

letters.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
canvas.textAlign = 'start';
4545
canvas.textBaseline = 'alphabetic';
4646

47-
var textWidth = function getWidth(value) {
47+
window.textWidth = function getWidth(value) {
4848
return canvas.measureText(value).width;
4949
}
5050

test/text_width_test.rb

+4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
it "should skip system characters" do
1919
assert_in_delta(FastExcel.arial_text_width(10.chr), 0.0)
2020
end
21+
22+
it "should handle multiline text" do
23+
assert_in_delta(FastExcel.arial_text_width("More\nThen\nOne Line"), 405.85, 0.1)
24+
end
2125
end
2226

2327
describe "FastExcel Calibri text_width" do

0 commit comments

Comments
 (0)