我想從FireStorage下載一個pdf檔案,渲染該檔案,將每一頁像ImageBitMap一樣添加到一個串列中,并在一個LazyColumn中顯示。問題是,滾動的速度非常慢,當頁面變化時甚至會凍結4-5秒。
有什么想法可以讓它更有效、更快?是否有一個用于JetPack Compose的庫,我可以使用它來使其更好?
謝謝你
PDFScreen.kt
@Composable
fun PDFScreen(obraId: ObraId, autorId: AuthorId){
val storageRef = FirebaseStorage.getInstance().reference
val pathReference = storageRef.child("obras/${autorId}/${obraId}.pdf" )
val localFile = File.createTempFile("obra"/span>, "pdf"/span>)
var imageList = remember { mutableStateListOf<ImageBitmap?> (null) }
pathReference.getFile(localFile).addOnSuccessListener {
imageList.clear()
if (it.task.isSuccessful) {
val input = ParcelFileDescriptor.open(localFile, ParcelFileDescriptor.MODE_READ_ONLY)
val renderer = PdfRenderer(input)
for (i in 0 until renderer.pageCount) {
val page = renderer.openPage(i)
val bitmap =
Bitmap.createBitmap(Constants.width, Constants.height, Bitmap.Config.ARGB_8888)
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
imageList.add(bitmap.asImageBitmap())
page.close()
}
渲染器.關閉()
}
}
LazyColumn(modifier = Modifier.fillMaxSize() ) {
items(items = imageList) { imagen ->
if (imagen != null) {
影像(
修改器 = 修改器
.fillMaxSize(), bitmap = imagen, contentDescription = "Prueba"
)
}
}
}
}
uj5u.com熱心網友回復:
你不應該直接從可組合函式中進行任何繁重的計算或資料庫/網路呼叫。
所有的復合函式都是視圖構造器,只要可改變狀態的值發生變化,就可以重新配置(例如,召回),而對于影片來說--最多每一幀。在你的代碼中,getFile查詢在一個新的專案被添加到可改變狀態的串列中時被執行,從而形成一個無盡的回圈。
我建議你從編譯中的狀態檔案開始,包括這個解釋基本原理的youtube視頻。
在你的案例中,這段代碼應該被移到視圖模型中:PDFScreenViewModel物件將在視圖出現時被創建,并在視圖離開視圖層次時被銷毀:
class PDFScreenViewModel: ViewModel() {
val imageList = mutableStateListOf<ImageBitmap?> (null)
private val storageRef = FirebaseStorage.getInstance() .reference
private val pathReference = storageRef. child("obras/${autorId}/${obraId}.pdf" )
private val localFile = File.createTempFile("obra", "pdf")
init {
加載()
}
fun load() {
pathReference.getFile(localFile).addOnSuccessListener {
imageList.clear()
if (it.task.isSuccessful) {
val input = ParcelFileDescriptor.open(localFile, ParcelFileDescriptor.MODE_READ_ONLY)
val renderer = PdfRenderer(input)
for (i in 0 until renderer.pageCount) {
val page = renderer.openPage(i)
val bitmap =
Bitmap.createBitmap(Constants.width, Constants.height, Bitmap.Config.ARGB_8888)
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
imageList.add(bitmap.asImageBitmap())
page.close()
}
渲染器.關閉()
}
}
}
}
@Composable
fun PDFScreen(obraId: ObraId, autorId: AuthorId){
val viewModel: PDFScreenViewModel = viewModel()
LazyColumn(modifier = Modifier.fillMaxSize() {
items(items = viewModel.imageList) { imagen ->
if (imagen != null) {
影像(
修改器 = 修改器
.fillMaxSize(), bitmap = imagen, contentDescription = "Prueba"
)
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/332809.html
標籤:
