android 加载长图 双击放大 手势缩放

使用的第三方框架

 //Glide
implementation "com.github.bumptech.glide:glide:4.9.0"
kapt "com.github.bumptech.glide:compiler:4.9.0"
//PhotoView 图片缩放
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
//subsampling-scale-image-view 加载长图
implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.10.0'
image.png

image.png

主要代码

private val MAX_SIZE = 4096
private val MAX_SCALE = 8

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    var imgUrl = arguments?.getString("imgUrl") ?: ""
    var position = arguments?.getInt("position")
    var imgUrlSize = arguments?.getInt("imgUrlSize")
    tvImageSizeView.setText("${(position ?: 0) + 1}/${imgUrlSize}")

    if (imgUrl != "") {
        if (ImageUtil.isGif(imgUrl)) {
            //加载动图
            Glide.with(this).load(imgUrl).into(photoViewImage)
        } else {
            downloadFile(imgUrl ?: "")
        }
    }

}

private fun downloadFile(imgUrl: String) {
    Glide.with(this).asBitmap().load(imgUrl)
        .into(object : BitmapImageViewTarget(photoViewImage) {

            @SuppressLint("CheckResult")
            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                super.onResourceReady(resource, transition)
                val h = resource.height
                val w = resource.width

                if (h >= MAX_SIZE || h / w > MAX_SCALE) {
                    photoViewImage.setVisibility(View.GONE)
                    photoViewSubsamplingScaleImage.setVisibility(View.VISIBLE)

                    Glide.with(this@ImageViewPagerFragment).load(imgUrl)
                        .downloadOnly(object : SimpleTarget<File>() {
                            override fun onResourceReady(
                                resource: File,
                                transition: Transition<in File>?
                            ) {
                                val scale = ImageUtil.getImageScale(
                                    this@ImageViewPagerFragment.context!!,
                                    resource.absolutePath
                                )
                                photoViewSubsamplingScaleImage.setImage(
                                    ImageSource.uri(resource.absolutePath),
                                    ImageViewState(scale, PointF(0f, 0f), 0)
                                )
                            }

                        })

                } else {
                    photoViewImage.setImageBitmap(resource)
                }
            }
        })

}

Demo地址:https://github.com/RookieExaminer/ScaleImage

推荐阅读更多精彩内容