leetomlee123 / book

笔趣阁源基于flutter的小说阅读app
Apache License 2.0
408 stars 99 forks source link

求教求教求教 #13

Closed zhatuokun closed 3 years ago

zhatuokun commented 3 years ago

小说分页是如何实现的呢,如何才能知道每页要显示多少个字符,本人新手小白,代码实在看不太懂。

可否简单跟我讲讲。

leetomlee123 commented 3 years ago

` void newPage([bool shouldJustifyHeight = true, bool lastPage = false]) { if (shouldJustifyHeight && this.shouldJustifyHeight) { final len = lines.length - startLine; double justify = (_height - dy) / (len - 1); for (var i = 0; i < len; i++) { lines[i + startLine].justifyDy(justify * i); } } if (columnNum == 1 || lastPage) { this.pages.add(TextPage(lines, dy)); lines = []; columnNum = 1; dx = _dx; } else { columnNum++; dx += columnWidth + 40; } dy = _dy; startLine = lines.length; }

/// 新段落
void newParagraph() {
  if (dy > _height2) {
    newPage();
  } else {
    dy += paragraph;
  }
}

for (var p in this.paragraphs) {
  while (true) {
    tp.text = TextSpan(text: p, style: style);
    tp.layout(maxWidth: columnWidth);
    final textCount = tp.getPositionForOffset(offset).offset;
    double spacing;
    final text = p.substring(0, textCount);
    if (tp.width > _width2) {
      tp.text = TextSpan(text: text, style: style);
      tp.layout();
      spacing = (_width - tp.width) / textCount;
    }
    lines.add(TextLine(text, dx, dy, spacing ?? 0));
    dy += tp.height;

    if (p.length == textCount) {
      newParagraph();
      break;
    } else {
      p = p.substring(textCount);
      if (dy > _height2) {
        newPage();
      }
    }
  }
}`

textpainter.layout 测算每行高度 并得到字符串下标

zhatuokun commented 3 years ago

奥,了解了。