Android加载网络长图的处理
加载普通网络图片时ImageLoader是很省事的,但是今天碰到个加载长图的问题,需要全屏显示还能滑动,自己实际测试+找资料解决了问题
下面说说思路:先根据图片地址转换成bitmap(有人会想到获得bitmap之后ImageView直接显示不就行了,but android手机蛋疼的地方到了,系统对bitmap的宽高有限制,比如我的小米4就是4065*4065,如果bitma宽高大于限制,就不会显示图片了),
把bitmap等分成几分,放在一个List<BitMap>集合里,然后循环动态加载ImageView并且显示bitmap。
下面贴代码:(可能会有遗漏的地方 希望大家指正)
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/ll_jl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
</LinearLayout>
</ScrollView>
</LinearLayout>
Java代码 用到了xUtils,可百度搜索
/**
* Created by yuLook on 2016/6/22.
*/
public class CeShiActivity extends BaseActivity {
@ViewInject(R.id.ll_jl)
private LinearLayout ll_jl;
private ArrayList<Bitmap>bitmapList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ceshi);
ViewUtils.inject(this);
//开始异步任务下载图片
asyncTask.execute();
}
private AsyncTask asyncTask=new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
try {
URL url=new URL("http://uefa.oss-cn-beijing.aliyuncs.com/ftx2016/jiangpin.png");
URLConnection connection=url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
int index=bitmap.getHeight()/2000+1;
bitmapList=new ArrayList<>();
for(int i=0;i<index;i++){
Bitmap bitmap3=Bitmap.createBitmap(bitmap,
0,
(int) ((double)bitmap.getHeight()/index*i),
bitmap.getWidth(),
(int) ((double) bitmap.getHeight()/index));
bitmapList.add(bitmap3);
}
//释放bitmap 不然会造成内存泄漏
bitmap.recycle();
bitmap=null;
//主线程发消息刷新界面
handler.sendEmptyMessage(index);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
};
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//清除异步任务
asyncTask.cancel(true);
if(bitmapList.size()>0){
Bitmap b = bitmapList.get(0);
//计算宽高比例
double a = (double) b.getHeight() / (double) b.getWidth();
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
(int) ((double)CommonTools.getScreenWidth(CeShiActivity.this)*a)
);
for(Bitmap bitmap:bitmapList){
ImageView imageView=new ImageView(CeShiActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(params);
imageView.setImageBitmap(bitmap);
ll_jl.addView(imageView);
}
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
//释放内存 防止内存泄漏造成内存溢出
for(Bitmap bitmap:bitmapList){
bitmap.recycle();
bitmap=null;
}
}
}