上述就是android开发分享Android不压缩图片实现高清加载巨图实例的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
一、概述
- 对于加载图片,大家都不陌生,一般为了尽可能避免oom都会按照如下做法:
- 对于图片显示:根据需要显示图片控件的大小对图片进行压缩显示。如果图片数量非常多:则会使用lrucache等缓存机制,将所有图片占据的内容维持在一个范围内。
其实对于图片加载还有种情况,就是单个图片非常巨大,并且还不允许压缩。比如显示:世界地图、清明上河图、微博长图等。
那么对于这种需求,该如何做呢?
首先不压缩,按照原图尺寸加载,那么屏幕肯定是不够大的,并且考虑到内存的情况,不可能一次性整图加载到内存中,所以肯定是局部加载,那么就需要用到一个类:
bitmapregiondecoder
其次,既然屏幕显示不完,那么最起码要添加一个上下左右拖动的手势,让用户可以拖动查看。
那么综上,本篇博文的目的就是去自定义一个显示巨图的view,支持用户去拖动查看,大概的效果图如下:
好吧,这清明上河图太长了,想要观看全图,文末下载,图片在assets目录。当然如果你的图,高度也很大,肯定也是可以上下拖动的。
二、初识bitmapregiondecoder
bitmapregiondecoder
主要用于显示图片的某一块矩形区域,如果你需要显示某个图片的指定区域,那么这个类非常合适。
对于该类的用法,非常简单,既然是显示图片的某一块区域,那么至少只需要一个方法去设置图片;一个方法传入显示的区域即可;详见:
bitmapregiondecoder提供了一系列的newinstance方法来构造对象,支持传入文件路径,文件描述符,文件的inputstrem等。
例如:
bitmapregiondecoder bitmapregiondecoder = bitmapregiondecoder.newinstance(inputstream, false);
上述解决了传入我们需要处理的图片,那么接下来就是显示指定的区域。
bitmapregiondecoder.decoderegion(rect, options);
参数一很明显是一个rect,参数二是bitmapfactory.options,你可以控制图片的insamplesize
,inpreferredconfig
等。
那么下面看一个超级简单的例子:
package com.zhy.blogcodes.largeimage;import android.graphics.bitmap;import android.graphics.bitmapfactory;import android.graphics.bitmapregiondecoder;import android.graphics.rect;import android.os.bundle;import android.support.v7.app.appcompatactivity;import android.widget.imageview;import com.zhy.blogcodes.r;import java.io.ioexception;import java.io.inputstream;public class largeimageviewactivity extends appcompatactivity{<!--{c}%3c!%2d%2d%20%2d%2d%3e--> private imageview mimageview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_large_image_view); mimageview = (imageview) findviewbyid(r.id.id_imageview); try { inputstream inputstream = getassets().open("tangyan.jpg"); //获得图片的宽、高 bitmapfactory.options tmpoptions = new bitmapfactory.options(); tmpoptions.injustdecodebounds = true; bitmapfactory.decodestream(inputstream, null, tmpoptions); int width = tmpoptions.outwidth; int height = tmpoptions.outheight; //设置显示图片的中心区域 bitmapregiondecoder bitmapregiondecoder = bitmapregiondecoder.newinstance(inputstream, false); bitmapfactory.options options = new bitmapfactory.options(); options.inpreferredconfig = bitmap.config.rgb_565; bitmap bitmap = bitmapregiondecoder.decoderegion(new rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options); mimageview.setimagebitmap(bitmap); } catch (ioexception e) { e.printstacktrace(); } }}package com.zhy.blogcodes.largeimage; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.graphics.bitmapregiondecoder; import android.graphics.rect; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.widget.imageview; import com.zhy.blogcodes.r; import java.io.ioexception; import java.io.inputstream; public class largeimageviewactivity extends appcompatactivity { private imageview mimageview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_large_image_view); mimageview = (imageview) findviewbyid(r.id.id_imageview); try { inputstream inputstream = getassets().open("tangyan.jpg"); //获得图片的宽、高 bitmapfactory.options tmpoptions = new bitmapfactory.options(); tmpoptions.injustdecodebounds = true; bitmapfactory.decodestream(inputstream, null, tmpoptions); int width = tmpoptions.outwidth; int height = tmpoptions.outheight; //设置显示图片的中心区域 bitmapregiondecoder bitmapregiondecoder = bitmapregiondecoder.newinstance(inputstream, false); bitmapfactory.options options = new bitmapfactory.options(); options.inpreferredconfig = bitmap.config.rgb_565; bitmap bitmap = bitmapregiondecoder.decoderegion(new rect(width / 2 - 100, height / 2 - 100, width / 2 + 100, height / 2 + 100), options); mimageview.setimagebitmap(bitmap); } catch (ioexception e) { e.printstacktrace(); } } }
上述代码,就是使用bitmapregiondecoder去加载assets中的图片,调用bitmapregiondecoder.decoderegion
解析图片的中间矩形区域,返回bitmap,最终显示在imageview上。
效果图:
上面的小图显示的即为下面的大图的中间区域。
ok,那么目前我们已经了解了bitmapregiondecoder
的基本用户,那么往外扩散,我们需要自定义一个控件去显示巨图就很简单了,首先rect的范围就是我们view的大小,然后根据用户的移动手势,不断去更新我们的rect的参数即可。
三、自定义显示大图控件
根据上面的分析呢,我们这个自定义控件思路就非常清晰了:
- 提供一个设置图片的入口
- 重写ontouchevent,在里面根据用户移动的手势,去更新显示区域的参数
- 每次更新区域参数后,调用invalidate,ondraw里面去regiondecoder.decoderegion拿到bitmap,去draw
理清了,发现so easy,下面上代码:
package com.zhy.blogcodes.largeimage.view; import android.content.context; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.graphics.bitmapregiondecoder; import android.graphics.canvas; import android.graphics.rect; import android.util.attributeset; import android.view.motionevent; import android.view.view; import java.io.ioexception; import java.io.inputstream; /** * created by zhy on 15/5/16. */ public class largeimageview extends view { private bitmapregiondecoder mdecoder; /** * 图片的宽度和高度 */ private int mimagewidth, mimageheight; /** * 绘制的区域 */ private volatile rect mrect = new rect(); private movegesturedetector mdetector; private static final bitmapfactory.options options = new bitmapfactory.options(); static { options.inpreferredconfig = bitmap.config.rgb_565; } public void setinputstream(inputstream is) { try { mdecoder = bitmapregiondecoder.newinstance(is, false); bitmapfactory.options tmpoptions = new bitmapfactory.options(); // grab the bounds for the scene dimensions tmpoptions.injustdecodebounds = true; bitmapfactory.decodestream(is, null, tmpoptions); mimagewidth = tmpoptions.outwidth; mimageheight = tmpoptions.outheight; requestlayout(); invalidate(); } catch (ioexception e) { e.printstacktrace(); } finally { try { if (is != null) is.close(); } catch (exception e) { } } } public void init() { mdetector = new movegesturedetector(getcontext(), new movegesturedetector.simplemovegesturedetector() { @override public boolean onmove(movegesturedetector detector) { int movex = (int) detector.getmovex(); int movey = (int) detector.getmovey(); if (mimagewidth > getwidth()) { mrect.offset(-movex, 0); checkwidth(); invalidate(); } if (mimageheight > getheight()) { mrect.offset(0, -movey); checkheight(); invalidate(); } return true; } }); } private void checkwidth() { rect rect = mrect; int imagewidth = mimagewidth; int imageheight = mimageheight; if (rect.right > imagewidth) { rect.right = imagewidth; rect.left = imagewidth - getwidth(); } if (rect.left < 0) { rect.left = 0; rect.right = getwidth(); } } private void checkheight() { rect rect = mrect; int imagewidth = mimagewidth; int imageheight = mimageheight; if (rect.bottom > imageheight) { rect.bottom = imageheight; rect.top = imageheight - getheight(); } if (rect.top < 0) { rect.top = 0; rect.bottom = getheight(); } } public largeimageview(context context, attributeset attrs) { super(context, attrs); init(); } @override public boolean ontouchevent(motionevent event) { mdetector.ontoucevent(event); return true; } @override protected void ondraw(canvas canvas) { bitmap bm = mdecoder.decoderegion(mrect, options); canvas.drawbitmap(bm, 0, 0, null); } @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { super.onmeasure(widthmeasurespec, heightmeasurespec); int width = getmeasuredwidth(); int height = getmeasuredheight(); int imagewidth = mimagewidth; int imageheight = mimageheight; //默认直接显示图片的中心区域,可以自己去调节 mrect.left = imagewidth / 2 - width / 2; mrect.top = imageheight / 2 - height / 2; mrect.right = mrect.left + width; mrect.bottom = mrect.top + height; } }
根据上述源码:
setinputstream里面去获得图片的真实的宽度和高度,以及初始化我们的mdecoder
onmeasure里面为我们的显示区域的rect赋值,大小为view的尺寸
ontouchevent里面我们监听move的手势,在监听的回调里面去改变rect的参数,以及做边界检查,最后invalidate
在ondraw里面就是根据rect拿到bitmap,然后draw了
ok,上面并不复杂,不过大家有没有注意到,这个监听用户move手势的代码写的有点奇怪,恩,这里模仿了系统的scalegesturedetector
,编写了movegesturedetector
,代码如下:
movegesturedetector
package com.zhy.blogcodes.largeimage.view; import android.content.context; import android.graphics.pointf; import android.view.motionevent; public class movegesturedetector extends basegesturedetector { private pointf mcurrentpointer; private pointf mprepointer; //仅仅为了减少创建内存 private pointf mdeltapointer = new pointf(); //用于记录最终结果,并返回 private pointf mextenalpointer = new pointf(); private onmovegesturelistener mlistenter; public movegesturedetector(context context, onmovegesturelistener listener) { super(context); mlistenter = listener; } @override protected void handleinprogressevent(motionevent event) { int actioncode = event.getaction() & motionevent.action_mask; switch (actioncode) { case motionevent.action_cancel: case motionevent.action_up: mlistenter.onmoveend(this); resetstate(); break; case motionevent.action_move: updatestatebyevent(event); boolean update = mlistenter.onmove(this); if (update) { mpremotionevent.recycle(); mpremotionevent = motionevent.obtain(event); } break; } } @override protected void handlestartprogressevent(motionevent event) { int actioncode = event.getaction() & motionevent.action_mask; switch (actioncode) { case motionevent.action_down: resetstate();//防止没有接收到cancel or up ,保险起见 mpremotionevent = motionevent.obtain(event); updatestatebyevent(event); break; case motionevent.action_move: mgestureinprogress = mlistenter.onmovebegin(this); break; } } protected void updatestatebyevent(motionevent event) { final motionevent prev = mpremotionevent; mprepointer = caculatefocalpointer(prev); mcurrentpointer = caculatefocalpointer(event); //log.e("tag", mprepointer.tostring() + " , " + mcurrentpointer); boolean mskipthismoveevent = prev.getpointercount() != event.getpointercount(); //log.e("tag", "mskipthismoveevent = " + mskipthismoveevent); mextenalpointer.x = mskipthismoveevent ? 0 : mcurrentpointer.x - mprepointer.x; mextenalpointer.y = mskipthismoveevent ? 0 : mcurrentpointer.y - mprepointer.y; } /** * 根据event计算多指中心点 * * @param event * @return */ private pointf caculatefocalpointer(motionevent event) { final int count = event.getpointercount(); float x = 0, y = 0; for (int i = 0; i < count; i++) { x += event.getx(i); y += event.gety(i); } x /= count; y /= count; return new pointf(x, y); } public float getmovex() { return mextenalpointer.x; } public float getmovey() { return mextenalpointer.y; } public interface onmovegesturelistener { public boolean onmovebegin(movegesturedetector detector); public boolean onmove(movegesturedetector detector); public void onmoveend(movegesturedetector detector); } public static class simplemovegesturedetector implements onmovegesturelistener { @override public boolean onmovebegin(movegesturedetector detector) { return true; } @override public boolean onmove(movegesturedetector detector) { return false; } @override public void onmoveend(movegesturedetector detector) { } } }
basegesturedetector
package com.zhy.blogcodes.largeimage.view; import android.content.context; import android.view.motionevent; public abstract class basegesturedetector { protected boolean mgestureinprogress; protected motionevent mpremotionevent; protected motionevent mcurrentmotionevent; protected context mcontext; public basegesturedetector(context context) { mcontext = context; } public boolean ontoucevent(motionevent event) { if (!mgestureinprogress) { handlestartprogressevent(event); } else { handleinprogressevent(event); } return true; } protected abstract void handleinprogressevent(motionevent event); protected abstract void handlestartprogressevent(motionevent event); protected abstract void updatestatebyevent(motionevent event); protected void resetstate() { if (mpremotionevent != null) { mpremotionevent.recycle(); mpremotionevent = null; } if (mcurrentmotionevent != null) { mcurrentmotionevent.recycle(); mcurrentmotionevent = null; } mgestureinprogress = false; } }
你可能会说,一个move手势搞这么多代码,太麻烦了。的确是的,move手势的检测非常简单,那么之所以这么写呢,主要是为了可以复用,比如现在有一堆的xxxgesturedetector
,当我们需要监听什么手势,就直接拿个detector来检测多方便。我相信大家肯定也郁闷过google,为什么只有scalegesturedetector
而没有rotategesturedetector
呢。
根据上述,大家应该理解了为什么要这么做,当时不强制,每个人都有个性。
不过值得一提的是:上面这个手势检测的写法,不是我想的,而是一个开源的项目
https://github.com/rharter/android-gesture-detectors
里面包含很多的手势检测。
对应的博文
那面上面两个类就是我偷学了的~ 哈
四、测试
测试其实没撒好说的了,就是把我们的largeimageview放入布局文件,然后activity里面去设置inputstream了。
<relativelayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.zhy.blogcodes.largeimage.view.largeimageview android:id="@+id/id_largetimageview" android:layout_width="match_parent" android:layout_height="match_parent"/> </relativelayout>
然后在activity里面去设置图片:
package com.zhy.blogcodes.largeimage; import android.os.bundle; import android.support.v7.app.appcompatactivity; import com.zhy.blogcodes.r; import com.zhy.blogcodes.largeimage.view.largeimageview; import java.io.ioexception; import java.io.inputstream; public class largeimageviewactivity extends appcompatactivity { private largeimageview mlargeimageview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_large_image_view); mlargeimageview = (largeimageview) findviewbyid(r.id.id_largetimageview); try { inputstream inputstream = getassets().open("world.jpg"); mlargeimageview.setinputstream(inputstream); } catch (ioexception e) { e.printstacktrace(); } } }
效果图:
ok,那么到此,显示巨图的方案以及详细的代码就描述完成了,总体还是非常简单的。
但是,在实际的项目中,可能会有更多的需求,比如增加放大、缩小;增加快滑手势等等,那么大家可以去参考这个库:
https://github.com/johnnylambada/worldmap
该库基本实现了绝大多数的需求,大家根据android开发分享Android不压缩图片实现高清加载巨图实例这个思路再去看这个库,也会简单很多,定制起来也容易。我这个地图的图就是该库里面提供的。
哈,掌握了这个,以后面试过程中也可以悄悄的装一把了,当你优雅的答完android加载图片的方案以后,然后接一句,其实还有一种情况,就是高清显示巨图,那么我们应该…相信面试官对你的印象会好很多~ have a nice day ~
源码点击下载
https://github.com/hongyangandroid/android_blog_demos
参考链接
https://github.com/johnnylambada/worldmap
https://github.com/rharter/android-gesture-detectors
以上就是android不压缩图片实现高清加载巨图实例的详细内容,更多关于android不压缩高清加载巨图的资料请关注<计算机技术网(www.ctvol.com)!!>其它相关文章!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/1105553.html