Set Background Image to Relative Layout using Glide in Android

后端 未结 7 591
逝去的感伤
逝去的感伤 2020-12-24 11:33

How can I do this using Glide? I want to cache image to use it another time also. Thanks in advance.

7条回答
  •  没有蜡笔的小新
    2020-12-24 12:13

    Glide.with(ctx).asBitmap().load(url).centerCrop().into(object: CustomTarget(){
                override fun onLoadCleared(placeholder: Drawable?) {
                }
    
                override fun onResourceReady(resource: Bitmap, transition: Transition?) {
                    val wRatio = view.width/resource.width.toFloat()
                    val hRatio = view.height / resource.height.toFloat()
    
                    val minRatio = min(wRatio,hRatio)
    
                    val destBitmap = Bitmap.createScaledBitmap( resource,(resource.width*minRatio).toInt(), (resource.height*minRatio).toInt(),false)
                   view.background = BitmapDrawable(resources,destBitmap)
                }
            })
    

    This works for me

    PS: There would be an error when the bitmap is too large

    java.lang.RuntimeException: Canvas: trying to draw too large bitmap.

    So you'd better scale that bitmap like what i did in above code

提交回复
热议问题