Android中加載上圖的方法
對於一些需要加載超長圖需求時,可能一開始使用使用bitmap或者inputstream轉bitmap(或類似加載庫)會發現出現圖片太大加載不出來的問題。
解決問題的思路可以參考Coding_the_world封裝自己的庫(然而我太菜了,就在網上找了一些開源庫),比較流行的是Subsampling Scale Image View,而且裏邊封裝了縮放功能。
實現思路是:使用glide把圖片下載到本地(由於我使用的就是glide圖片加載庫),然後賦值。具體的操作如下:
1.在gradle文件中添加依賴
compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.5.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
2.在具體代碼中的配置
imageView = (SubsamplingScaleImageView) findViewById(R.id.imageView);
imageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
imageView.setMinScale(1.0F);
finalString testUrl ="http://cache.attach.yuanobao.com/image/2016/10/24/332d6f3e63784695a50b782a38234bb7/da0f06f8358a4c95921c00acfd675b60.jpg";
finalFile downDir = Environment.getExternalStorageDirectory();
//下載圖片保存到本地
Glide.with(this)
.load(testUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource,
GlideAnimation<? super Bitmap> glideAnimation) {
File file = new File(downDir, "/da0f06f8358a4c95921c00acfd675b60.jpg");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fout = null;
try {
//保存圖片
fout = new FileOutputStream(file);
resource.compress(Bitmap.CompressFormat.JPEG, 100, fout);
// 將保存的圖片地址給SubsamplingScaleImageView,這裏注意設置ImageViewState設置初始顯示比例
imageView.setImage(ImageSource.uri(file.getAbsolutePath()), new ImageViewState(0.5F, new PointF(0, 0), 0));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fout != null) fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});