下面是一个使用 Glide 加载网络图片,并根据图片宽高自适应等比例显示的自定义 ImageView 的示例代码:

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.DrawableImageViewTarget
import com.bumptech.glide.request.transition.Transition

class CustomImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    fun loadImage(url: String) {
        Glide.with(context)
            .load(url)
            .into(object : DrawableImageViewTarget(this) {
                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    super.onResourceReady(resource, transition)
                    adjustImageAspect(resource)
                }

                private fun adjustImageAspect(drawable: Drawable) {
                    val imgWidth = drawable.intrinsicWidth
                    val imgHeight = drawable.intrinsicHeight
                    val aspectRatio = imgWidth.toFloat() / imgHeight

                    val newWidth: Int
                    val newHeight: Int

                    if (width > height) {
                        newWidth = width
                        newHeight = (width / aspectRatio).toInt()
                    } else {
                        newWidth = (height * aspectRatio).toInt()
                        newHeight = height
                    }

                    val layoutParams = layoutParams
                    layoutParams.width = newWidth
                    layoutParams.height = newHeight
                    setLayoutParams(layoutParams)
                }
            })
    }
}

在上述代码中,我们创建了一个名为 'CustomImageView' 的自定义 ImageView,其中的 'loadImage' 函数用于加载网络图片并自适应等比例显示。我们使用 Glide 库来加载图片,并使用 'DrawableImageViewTarget' 来监听图片加载完成的回调。

在 'onResourceReady' 方法中,我们首先调用 'super.onResourceReady' 来设置图片资源,并接着调用 'adjustImageAspect' 方法来调整图片的宽高比例。

在 'adjustImageAspect' 方法中,我们首先获取图片的宽度和高度,然后计算出图片的宽高比例。接着根据 'CustomImageView' 的宽高比例来调整新的宽高。最后,我们更新 'CustomImageView' 的 LayoutParams 来使其适应新的宽高。

要使用这个自定义 ImageView,你可以在布局文件中添加以下代码:

<com.example.app.CustomImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />

然后在代码中使用以下代码加载网络图片:

val imageView = findViewById<CustomImageView>(R.id.imageView)
imageView.loadImage('https://example.com/image.jpg')

请注意,你需要将 'https://example.com/image.jpg' 替换为你实际的图片 URL。同时,你还需要将 Glide 库添加到你的项目中。你可以在 'build.gradle' 文件中添加以下代码来引入 Glide 库:

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.13.0'
    kapt 'com.github.bumptech.glide:compiler:4.13.0'
}

希望以上代码能帮助到你!


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

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