Android编程实现的超炫图片浏览器
本文实例讲述了android编程实现的超炫图片浏览器。分享给大家供大家参考,具体如下:
使用过android自带的gallery组件的人都知道,gallery实现的效果就是拖动浏览一组图片,相比iphone里也是用于拖动浏览图片的coverflow,显然逊色不少。实际上,可以通过扩展gallery,通过伪3d变换可以基本实现coverflow的效果。本文通过源代码解析这一功能的实现。具体代码作用可参照注释。
最终实现效果如下:
要使用gallery,我们必须首先给其指定一个adapter。在这里,我们实现了一个自定义的imageadapter,为图片制作倒影效果。
传入参数为context和程序内drawable中的图片id数组。之后调用其中的createreflectedimages()方法分别创造每一个图像的倒影效果,生成对应的imageview数组,最后在getview()中返回。
copyright (c) 2010 neil davies * * licensed under the apache license, version 2.0 (the "license"); * you may not use this file except in compliance with the license. * you may obtain a copy of the license at * * [url]http://www.apache.org/licenses/license-2.0[/url] * * unless required by applicable law or agreed to in writing, software * distributed under the license is distributed on an "as is" basis, * without warranties or conditions of any kind, either express or implied. * see the license for the specific language governing permissions and * limitations under the license. * * this code is base on the android gallery widget and was created * by neil davies neild001 'at' gmail dot com to be a coverflow widget * * @author neil davies */ public class imageadapter extends baseadapter { int mgalleryitembackground; private context mcontext; private integer[] mimageids ; private imageview[] mimages; public imageadapter(context c, int[] imageids) { mcontext = c; mimageids = imageids; mimages = new imageview[mimageids.length]; } public boolean createreflectedimages() { // the gap we want between the reflection and the original image final int reflectiongap = 4; int index = 0; for (int imageid : mimageids) { bitmap originalimage = bitmapfactory.decoderesource( mcontext.getresources(), imageid); int width = originalimage.getwidth(); int height = originalimage.getheight(); // this will not scale but will flip on the y axis matrix matrix = new matrix(); matrix.prescale(1, -1); // create a bitmap with the flip matrix applied to it. // we only want the bottom half of the image bitmap reflectionimage = bitmap.createbitmap(originalimage, 0, height / 2, width, height / 2, matrix, false); // create a new bitmap with same width but taller to fit // reflection bitmap bitmapwithreflection = bitmap.createbitmap(width, (height + height / 2), config.argb_8888); // create a new canvas with the bitmap that's big enough for // the image plus gap plus reflection canvas canvas = new canvas(bitmapwithreflection); // draw in the original image canvas.drawbitmap(originalimage, 0, 0, null); // draw in the gap paint deafaultpaint = new paint(); canvas.drawrect(0, height, width, height + reflectiongap, deafaultpaint); // draw in the reflection canvas.drawbitmap(reflectionimage, 0, height + reflectiongap, null); // create a shader that is a linear gradient that covers the // reflection paint paint = new paint(); lineargradient shader = new lineargradient(0, originalimage.getheight(), 0, bitmapwithreflection.getheight() + reflectiongap, 0x70ffffff, 0x00ffffff, tilemode.clamp); // set the paint to use this shader (linear gradient) paint.setshader(shader); // set the transfer mode to be porter duff and destination in paint.setxfermode(new porterduffxfermode(mode.dst_in)); // draw a rectangle using the paint with our linear gradient canvas.drawrect(0, height, width, bitmapwithreflection.getheight() + reflectiongap, paint); imageview imageview = new imageview(mcontext); imageview.setimagebitmap(bitmapwithreflection); imageview .setlayoutparams(new galleryflow.layoutparams(160, 240)); // imageview.setscaletype(scaletype.matrix); mimages[index++] = imageview; } return true; } public int getcount() { return mimageids.length; } public object getitem(int position) { return position; } public long getitemid(int position) { return position; } public view getview(int position, view convertview, viewgroup parent) { // use this code if you want to load from resources /* * imageview i = new imageview(mcontext); * i.setimageresource(mimageids[position]); i.setlayoutparams(new * coverflow.layoutparams(350,350)); * i.setscaletype(imageview.scaletype.center_inside); * * //make sure we set anti-aliasing otherwise we get jaggies * bitmapdrawable drawable = (bitmapdrawable) i.getdrawable(); * drawable.setantialias(true); return i; */ return mimages[position]; } /** * returns the size (0.0f to 1.0f) of the views depending on the * 'offset' to the center. */ public float getscale(boolean focused, int offset) { /* formula: 1 / (2 ^ offset) */ returnmath.max(0,1.0f / (float) math.pow(2, math.abs(offset))); } } }
仅仅实现了图片的倒影效果还不够,因为在coverflow中图片切换是有旋转和缩放效果的,而自带的gallery中并没有实现。因此,我们扩展自带的gallery,实现自己的galleryflow。在原gallery类中,提供了一个方法getchildstatictransformation()以实现对图片的变换。我们通过覆写这个方法并在其中调用自定义的transformimagebitmap(“每个图片与gallery中心的距离”)方法,,即可实现每个图片做相应的旋转和缩放。其中使用了camera和matrix用于视图变换。具体可参考代码注释。
public class galleryflow extendsgallery { /** * graphics camera used for transforming the matrix of imageviews */ privatecamera mcamera = newcamera(); /** * the maximum angle the child imageview will be rotated by */ privateint mmaxrotationangle =60; /** * the maximum zoom on the centre child */ privateint mmaxzoom = -120; /** * the centre of the coverflow */ privateint mcoveflowcenter; publicgalleryflow(context context) { super(context); this.setstatictransformationsenabled(true); } publicgalleryflow(context context, attributeset attrs) { super(context, attrs); this.setstatictransformationsenabled(true); } publicgalleryflow(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); this.setstatictransformationsenabled(true); } /** * get the max rotational angle of the image * * @return the mmaxrotationangle */ publicint getmaxrotationangle() { returnmmaxrotationangle; } /** * set the max rotational angle of each image * * @param maxrotationangle * the mmaxrotationangle to set */ publicvoid setmaxrotationangle(intmaxrotationangle) { mmaxrotationangle = maxrotationangle; } /** * get the max zoom of the centre image * * @return the mmaxzoom */ publicint getmaxzoom() { returnmmaxzoom; } /** * set the max zoom of the centre image * * @param maxzoom * the mmaxzoom to set */ publicvoid setmaxzoom(intmaxzoom) { mmaxzoom = maxzoom; } /** * get the centre of the coverflow * * @return the centre of this coverflow. */ privateint getcenterofcoverflow() { return(getwidth() - getpaddingleft() - getpaddingright()) / 2 + getpaddingleft(); } /** * get the centre of the view * * @return the centre of the given view. */ privatestatic int getcenterofview(view view) { returnview.getleft() + view.getwidth() / 2; } /** * {@inheritdoc} * * @see #setstatictransformationsenabled(boolean) */ protectedboolean getchildstatictransformation(view child, transformation t) { finalint childcenter = getcenterofview(child); finalint childwidth = child.getwidth(); introtationangle = 0; t.clear(); t.settransformationtype(transformation.type_matrix); if(childcenter == mcoveflowcenter) { transformimagebitmap((imageview) child, t,0); }else { rotationangle = (int) (((float) (mcoveflowcenter - childcenter) / childwidth) * mmaxrotationangle); if(math.abs(rotationangle) > mmaxrotationangle) { rotationangle = (rotationangle <0) ? -mmaxrotationangle : mmaxrotationangle; } transformimagebitmap((imageview) child, t, rotationangle); } returntrue; } /** * this is called during layout when the size of this view has changed. if * you were just added to the view hierarchy, you're called with the old * values of 0. * * @param w * current width of this view. * @param h * current height of this view. * @param oldw * old width of this view. * @param oldh * old height of this view. */ protectedvoid onsizechanged(intw, int h, int oldw, int oldh) { mcoveflowcenter = getcenterofcoverflow(); super.onsizechanged(w, h, oldw, oldh); } /** * transform the image bitmap by the angle passed * * @param imageview * imageview the imageview whose bitmap we want to rotate * @param t * transformation * @param rotationangle * the angle by which to rotate the bitmap */ privatevoid transformimagebitmap(imageview child, transformation t, introtationangle) { mcamera.save(); finalmatrix imagematrix = t.getmatrix(); finalint imageheight = child.getlayoutparams().height; finalint imagewidth = child.getlayoutparams().width; finalint rotation = math.abs(rotationangle); // 在z轴上正向移动camera的视角,实际效果为放大图片。 // 如果在y轴上移动,则图片上下移动;x轴上对应图片左右移动。 mcamera.translate(0.0f,0.0f, 100.0f); // as the angle of the view gets less, zoom in if(rotation < mmaxrotationangle) { floatzoomamount = (float) (mmaxzoom + (rotation *1.5)); mcamera.translate(0.0f,0.0f, zoomamount); } // 在y轴上旋转,对应图片竖向向里翻转。 // 如果在x轴上旋转,则对应图片横向向里翻转。 mcamera.rotatey(rotationangle); mcamera.getmatrix(imagematrix); imagematrix.pretranslate(-(imagewidth /2), -(imageheight /2)); imagematrix.posttranslate((imagewidth /2), (imageheight /2)); mcamera.restore(); } }
代码到这里就结束了。有兴趣的话可以自行调整里面的参数来实现更多更炫的效果。
下面是调用的示例:
public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.layout_gallery); integer[] images = { r.drawable.img0001, r.drawable.img0030, r.drawable.img0100, r.drawable.img0130, r.drawable.img0200, r.drawable.img0230, r.drawable.img0300, r.drawable.img0330, r.drawable.img0354 }; imageadapter adapter =new imageadapter(this, images); adapter.createreflectedimages(); galleryflow galleryflow = (galleryflow) findviewbyid(r.id.gallery_flow); galleryflow.setadapter(adapter); }
ps1:
可以看出来这样实现的gallery锯齿问题比较严重。可以在createreflectedimages()使用以下代码:
bitmapdrawable bd = new bitmapdrawable(bitmapwithreflection); bd.setantialias(true);
然后用iv.setimagedrawable(bd);
代替iv.setimagebitmap(bitmapwithreflection);
即可基本消除锯齿。
ps2:
imageadapter有待确定的memoryleak问题,貌似的bitmap的decode方法会造成ml,使用imageadapter时多次旋转屏幕后会出现oom。目前可以通过将使用完毕的bimap调用recycle()方法和设置null并及时调用system.gc()得到一些改善,但是问题并不明显。
庆祝精华和推荐,增加3个ps~
ps3 on ps1:
为什么开启抗锯齿后不明显。答案是,锯齿不可能完全消除,但开启抗锯齿后会有很大改善。
另外还说到为什么android不默认开启锯齿,以下是我的一点想法:
插值是我现在所知道的抗锯齿的算法,也就是计算像素间的相关度对其间插入中间像素以达到平滑图像边缘的效果。但这无疑会耗费了大量的运算。
虽然我没有经过测试,但是我猜测,使用antialias后图形性能至少会下降30%。
当然,在这里没有涉及到复杂的图形运算,所以开启抗锯齿不会有很明显的性能影响,但如果你在模拟器或者低端机型上测试就会发现一点问题。
ps4:
有人问到transformimagebitmap()中这俩句话是什么意思:
imagematrix.pretranslate(-(imagewidth / 2), -(imageheight / 2)); imagematrix.posttranslate((imagewidth / 2), (imageheight / 2));
个人的理解如下:
pretranslate相当于在对图像进行任何矩阵变换前先进行pretranslate,posttranslate相反,进行所有变换后再执行posttranlate。
这俩句的意思是:在做任何变换前,先将整个图像从图像的中心点移动到原点((0,0)点),执行变换完毕后再将图像从原点移动到之前的中心点。
如果不加这俩句,任何变换将以图像的原点为变换中心点,加了之后,任何变换都将以图像的中心点为变换中心点。
举个例子,对图像进行旋转,需要俩个参数:一个是旋转的角度,另一个是旋转中心的坐标。旋转中心的坐标影响旋转的效果。这个能明白吗?你拿一根棍子,拿着棍子的一端进行旋转和拿在棍子中间旋转,是不一样的。pretranslate和posttranslate执行后对图像本身不会有影响,影响的是对图像进行变换时的旋转轴。
说了这么多有点绕,其实就是矩阵变换的知识。
ps5 on ps2:
这个问题在google group下有过很充分的讨论,貌似一般只在debug模式下存在。现在我使用这段代码没有出现oom问题了
希望本文所述对大家android程序设计有所帮助。