需求:
有一张图片:清明上河图,尺寸为:19920*720;将该图片放置在mipmap目录下;要将该图片显示在ImageView上,避免发生OOM;
实现步骤:
1.分析:
一张分辨率为19920*720,解码格式为ARGB_888的图片占用的内存大小为:19920*720*8/1024/1024(MB),大概为100多MB,加载如此一张图片占用的内存过大,极易造成OOM;
2.实现:
①获取InputStream输入流对象(将对应的资源文件图片转为输入流对象):
inputStream = getResources().openRawResource(R.mipmap.qmsht);
②获取BitmapRegionDecoder对象:
bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);③获取截取的区域位置:
private int imgWidth = 1080; private int imgHeight = 300; private int bitmap_width = 0; private int bitmap_height = 0;
int top = 0; int right = imgWidth + left; int bottom = imgHeight;
bitmap = bitmapRegionDecoder.decodeRegion(new Rect(left, top, right, bottom), options); iv.setImageBitmap(bitmap);④获取图片的宽高:private void getBitmapMsg() { BitmapFactory.Options options = new BitmapFactory.Options(); //只decode图片宽高等信息: options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(), R.mipmap.qmsht, options); bitmap_width = options.outWidth; bitmap_height = options.outHeight; }
⑤设置定时器,每隔0.1秒,截取的区域向右移动1000像素;
private int step = 1000; private int left = 0;
private Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { if (left < bitmap_width - imgWidth) { int last_width = bitmap_width - left - imgWidth; step = last_width < step ? last_width : step; left += step; setBitmap02(); handler.postDelayed(this, 100); } else { Toast.makeText(MainActivity.this, "结束!", Toast.LENGTH_SHORT).show(); } }
最后:效果图如下:
};