要使用Glide加载网络图片,并获取图片的宽高并设置到ImageView上,可以按照以下步骤进行操作:

  1. 在app的build.gradle文件中添加Glide依赖:
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
  1. 在需要加载图片的Activity或Fragment中,找到要加载图片的ImageView:
val imageView = findViewById<ImageView>(R.id.imageView)
  1. 使用Glide加载图片,并设置监听器获取图片的宽高:
Glide.with(this)
    .load("your_image_url")
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            val width = resource?.intrinsicWidth
            val height = resource?.intrinsicHeight
            
            // 设置图片宽高到ImageView
            imageView.layoutParams.width = width
            imageView.layoutParams.height = height
            imageView.setImageDrawable(resource)
            
            return false
        }
    })
    .into(imageView)
  1. 注意:在设置图片宽高到ImageView时,需要将宽高值设置到ImageView的LayoutParams中,再将LayoutParams设置回ImageView。

这样就能使用Glide加载网络图片,并获取图片的宽高并设置到ImageView上了

Android kotlin glide加载网络图片 获取图片宽高 并设置着imageView上

原文地址: http://www.cveoy.top/t/topic/iJYl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录