Skip to content

Commit

Permalink
Merge pull request jasondu#92 from chuyun/master
Browse files Browse the repository at this point in the history
fix:多行文字计算换行问题修复
  • Loading branch information
jasondu authored Mar 18, 2019
2 parents c0332af + 2191a68 commit 35a8b81
Showing 1 changed file with 25 additions and 17 deletions.
42 changes: 25 additions & 17 deletions miniprogram_dist/index/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,26 +185,34 @@ const handle = {
this.ctx.setTextAlign(textAlign);
let textWidth = this.toRpx(this.ctx.measureText(text).width);
const textArr = [];
if (textWidth > width) {
// 文本宽度 大于 渲染宽度
const unitTextWidth = +(textWidth / text.length).toFixed(2);
const unitLineNum = parseInt(width / unitTextWidth); // 一行文本数量
for (let i = 0; i <= text.length; i += unitLineNum) { // 将文字转为数组,一行文字一个元素
const resText = text.slice(i, i + unitLineNum);
resText !== '' && textArr.push(resText);
if (textArr.length === lineNum) {
break;
if (textWidth > width) {
// 文本宽度 大于 渲染宽度
let fillText = '';
let line = 1;
for (let i = 0; i <= text.length - 1 ; i++) { // 将文字转为数组,一行文字一个元素
fillText = fillText + text[i];
if (this.toRpx(this.ctx.measureText(fillText).width) >= width) {
if (line === lineNum) {
if (i !== text.length - 1) {
fillText = fillText.substring(0, fillText.length - 1) + '...';
}
}
if(line <= lineNum) {
textArr.push(fillText);
}
fillText = '';
line++;
} else {
if(line <= lineNum) {
if(i === text.length -1){
textArr.push(fillText);
}
}
}
if (textArr.length * unitLineNum < text.length) {
const moreTextWidth = this.ctx.measureText('...').width;
const moreTextNum = Math.ceil(moreTextWidth / unitTextWidth);
const reg = new RegExp(`.{${moreTextNum}}$`);
textArr[textArr.length - 1] = textArr[textArr.length - 1].replace(reg, '...');
}
textWidth = width;
}
textWidth = width;
} else {
textArr.push(text);
textArr.push(text);
}

textArr.forEach((item, index) => {
Expand Down

0 comments on commit 35a8b81

Please sign in to comment.