Using Facebook's Fresco to load a bitmap

后端 未结 5 1048
自闭症患者
自闭症患者 2020-12-06 01:59

I\'m trying to replace Picasso in my android app with Fresco. However I am unsure of how to simply load a bitmap using Fresco.

With Picasso I would just do the foll

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 02:15

    Starting from this answer I created a quick implementation that uses Kotlin extensions and RxJava to get a ClosableBitmap from an ImageRequest:

    fun ImageRequest.getBitmap(context: Context): Maybe> {
        val dataSource = Fresco.getImagePipeline().fetchDecodedImage(this, context)
        return Maybe.create { emitter ->
            dataSource.subscribe(
                object : BaseDataSubscriber>() {
                    override fun onFailureImpl(dataSource: DataSource>) {
                        emitter.onComplete()
                    }
    
                    override fun onNewResultImpl(dataSource: DataSource>) {
                        if (!dataSource.isFinished) {
                            return
                        }
    
                        dataSource.result
                            ?.takeIf { it.get() is CloseableBitmap }
                            ?.let {
                                @Suppress("UNCHECKED_CAST")
                                emitter.onSuccess(it as CloseableReference)
                            }
    
                        emitter.onComplete()
                    }
                },
                DefaultExecutorSupplier(1).forBackgroundTasks()
            )
        }
    }
    

    Since by contract it is required to close the reference once the bitmap has been used, I created this util function:

    /**
     * The bitmap passed into [block] is only valid during the execution of the method.
     */
    fun  CloseableReference.useBitmap(block: (Bitmap?) -> T): T? {
        return try {
            this.get()?.underlyingBitmap?.let { block(it) }
        } finally {
            CloseableReference.closeSafely(this)
        }
    }
    

提交回复
热议问题