記錄一下寫小說閱讀器過程中遇到的一些問題及解決方案。
首先第一個問題就是小說的分頁。
如何分頁
這里可以通過 ViewPager 來進行分頁,但是 Compose 中并沒有 ViewPager浇垦,經(jīng)過我的尋找,找到了一個 Compose 中的 ViewPager荣挨,是 google 出的一個庫男韧。
https://google.github.io/accompanist/pager/
接下來就是第二個問題,如何確定一頁的大小默垄。也就是確定一頁能夠顯示的字數(shù)此虑。
確定一頁能夠顯示的字數(shù)
這個也比較困難,因為 Compose 中的 Text 并沒有暴露出太多的 api口锭,所以也是比較困難的朦前,最終在 https://my.oschina.net/gotax/blog/136860 這篇文章的啟發(fā)下找到了解決辦法介杆。
@ExperimentalPagerApi
@Preview
@Composable
fun PageTest() {
Box(
modifier = Modifier
.fillMaxSize()
) {
val pageState = rememberPagerState(pageCount = 100, infiniteLoop = true)
HorizontalPager(
state = pageState,
modifier = Modifier.fillMaxHeight(),
verticalAlignment = Alignment.Top,
horizontalAlignment = Alignment.Start
) { state ->
Box(
modifier = Modifier
.fillMaxSize()
.graphicsLayer {
// Calculate the absolute offset for the current page from the
// scroll position. We use the absolute value which allows us to mirror
// any effects for both directions
val pageOffset = calculateCurrentOffsetForPage(state).absoluteValue
// We animate the scaleX + scaleY, between 85% and 100%
lerp(
start = 0.85f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
).also { scale ->
scaleX = scale
scaleY = scale
}
// We animate the alpha, between 50% and 100%
alpha = lerp(
start = 0.5f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
)
}
) {
Column {
val sb = StringBuilder()
repeat(state * 10) {
sb.append("阿a達")
}
var totalNumState by remember {
mutableStateOf(0)
}
Text(
text = "Page: $state current page = ${pageState.currentPage}",
)
Text(text = "$totalNumState")
Text(
onTextLayout = {
try {
val lineNum =
it.getLineForVerticalPosition(it.size.height.toFloat())
if (lineNum != 0) {
val totalNum = it.getLineEnd(lineNum, false)
Log.d(
"PageTest",
"line Number = $lineNum, line end totalNum = $totalNum str = ${sb.toString().length}"
)
totalNumState = totalNum
}
} catch (e: Exception) {
e.printStackTrace()
}
},
text = sb.toString()
)
}
}
}
}
}