SubsamplingScaleImageView是一个图片浏览库,支持点击和缩放,支持长图和超大图。
导入库
dependencies {
implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.10.0'
// androidx项目使用
implementation 'com.davemorrissey.labs:subsampling-scale-image-view-androidx:3.10.0'
}
布局文件引用SubsamplingScaleImageView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
SubsamplingScaleImageView
使用ImageSource
来加载图片
setImage(@NonNull ImageSource imageSource)
setImage(@NonNull ImageSource imageSource, ImageViewState state)
setImage(@NonNull ImageSource imageSource, ImageSource previewSource)
setImage(@NonNull ImageSource imageSource, ImageSource previewSource, ImageViewState state)
ImageSource
目前只支持本土访问,可配合图片管理工具使用
ImageSource resource(int resId)
ImageSource asset(@NonNull String assetName)
ImageSource uri(@NonNull String uri)
ImageSource uri(@NonNull Uri uri)
ImageSource bitmap(@NonNull Bitmap bitmap)
加载后的图片会居中显示,
如果加载的是长图,图片也会居中显示,为了让图片适应宽度,我们可以设置minimumScaleType
和minScale
,并指定起始位置
var imageView: SubsamplingScaleImageView = findViewById(R.id.image_view)
var bitmap = BitmapFactory.decodeResource(resources, R.drawable.long_pic)
var dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
imageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_CROP)
imageView.minScale = bitmap.width/dm.widthPixels.toFloat()
imageView.setImage(ImageSource.bitmap(bitmap), ImageViewState(0f, PointF(0f, 0f), 0))
显示如下
github地址: https://github.com/davemorrissey/subsampling-scale-image-view