【问题标题】:how can i improve these functions to bind bitmaps on recyclerView?如何改进这些功能以在 recyclerView 上绑定位图?
【发布时间】:2020-07-11 19:31:30
【问题描述】:

我有一组两个函数,用于将图像绑定到回收视图,一个用于将字符串(base64)转换为位图,另一个函数是将所述图像的角变圆。

 //convert string to bitmap
    fun stringToBitMap( encodedString: String): Bitmap? {
        println("string to bitmap is being called")
        return try {
            val encodeByte: ByteArray = Base64.decode(encodedString, Base64.DEFAULT)
            BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.size)
        } catch (e: Exception) {
            println("Failed to convert string to bitmap")
            e.message
            null
        }
    }
    
    //round corners
    fun getRoundedCornerBitmap(bitmap: Bitmap, pixels: Int): Bitmap {
        println("get rounded corners is being called")
        val output = Bitmap.createBitmap(bitmap.width, bitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        val color = -0xbdbdbe
        val paint = Paint()
        val rect = Rect(0, 0, bitmap.width, bitmap.height)
        val rectF = RectF(rect)
        val roundPx = pixels.toFloat()
        paint.isAntiAlias = true
        canvas.drawARGB(0, 0, 0, 0)
        paint.color = color
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint)
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(bitmap, rect, rect, paint)
        return output
    }

我用 BindingAdapter 注释了我的最终函数,然后我从 xml 文件中调用该函数

 @BindingAdapter("poster")
    fun image (view: ImageView, image: String) {
        return view.setImageBitmap(stringToBitMap(image)?.let { getRoundedCornerBitmap(it, 10) })
    }

它可以工作,但在某些设备上性能很差,我在低资源手机(三星 SM-J106B)中调试我的应用程序,快速滚动时 CPU 使用率峰值为 35%(我的图像不是高分辨率,只有 400x400),recyclerview 也不断调用这些函数,这使得滚动有点迟缓。那么问题来了,我该如何改进我的功能呢?

pd: 我是个新手 :(

【问题讨论】:

    标签: android kotlin android-recyclerview bitmap base64


    【解决方案1】:

    我最终使用了这样的滑翔:

        fun poster(view: ImageView, image: String) {
        val imageByteArray: ByteArray = Base64.decode(image, Base64.DEFAULT)
        val round = RequestOptions
            .bitmapTransform(RoundedCorners(14))
    
        Glide.with(view)
            .load(imageByteArray)
            .apply(round)
            .into(view)
    }
    

    现在性能更好了:D

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 2021-05-03
      • 1970-01-01
      • 2022-01-06
      • 2011-04-23
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多