Android编程实现的超炫图片浏览器
本文实例讲述了Android编程实现的超炫图片浏览器。分享给大家供大家参考,具体如下:
使用过Android自带的gallery组件的人都知道,gallery实现的效果就是拖动浏览一组图片,相比iphone里也是用于拖动浏览图片的coverflow,显然逊色不少。实际上,可以通过扩展gallery,通过伪3D变换可以基本实现coverflow的效果。本文通过源代码解析这一功能的实现。具体代码作用可参照注释。
最终实现效果如下:
要使用gallery,我们必须首先给其指定一个adapter。在这里,我们实现了一个自定义的ImageAdapter,为图片制作倒影效果。
传入参数为context和程序内drawable中的图片ID数组。之后调用其中的createReflectedImages()方法分别创造每一个图像的倒影效果,生成对应的ImageView数组,最后在getView()中返回。
Copyright(C)2010NeilDavies
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*[url]http://www.apache.org/licenses/LICENSE-2.0[/url]
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*
*ThiscodeisbaseontheAndroidGallerywidgetandwasCreated
*byNeilDaviesneild001'at'gmaildotcomtobeaCoverflowwidget
*
*@authorNeilDavies
*/
publicclassImageAdapterextendsBaseAdapter{
intmGalleryItemBackground;
privateContextmContext;
privateInteger[]mImageIds;
privateImageView[]mImages;
publicImageAdapter(Contextc,int[]ImageIds){
mContext=c;
mImageIds=ImageIds;
mImages=newImageView[mImageIds.length];
}
publicbooleancreateReflectedImages(){
//Thegapwewantbetweenthereflectionandtheoriginalimage
finalintreflectionGap=4;
intindex=0;
for(intimageId:mImageIds){
BitmaporiginalImage=BitmapFactory.decodeResource(
mContext.getResources(),imageId);
intwidth=originalImage.getWidth();
intheight=originalImage.getHeight();
//ThiswillnotscalebutwillflipontheYaxis
Matrixmatrix=newMatrix();
matrix.preScale(1,-1);
//CreateaBitmapwiththeflipmatrixappliedtoit.
//Weonlywantthebottomhalfoftheimage
BitmapreflectionImage=Bitmap.createBitmap(originalImage,0,
height/2,width,height/2,matrix,false);
//Createanewbitmapwithsamewidthbuttallertofit
//reflection
BitmapbitmapWithReflection=Bitmap.createBitmap(width,
(height+height/2),Config.ARGB_8888);
//CreateanewCanvaswiththebitmapthat'sbigenoughfor
//theimageplusgapplusreflection
Canvascanvas=newCanvas(bitmapWithReflection);
//Drawintheoriginalimage
canvas.drawBitmap(originalImage,0,0,null);
//Drawinthegap
PaintdeafaultPaint=newPaint();
canvas.drawRect(0,height,width,height+reflectionGap,
deafaultPaint);
//Drawinthereflection
canvas.drawBitmap(reflectionImage,0,height+reflectionGap,
null);
//Createashaderthatisalineargradientthatcoversthe
//reflection
Paintpaint=newPaint();
LinearGradientshader=newLinearGradient(0,
originalImage.getHeight(),0,
bitmapWithReflection.getHeight()+reflectionGap,
0x70ffffff,0x00ffffff,TileMode.CLAMP);
//Setthepainttousethisshader(lineargradient)
paint.setShader(shader);
//SettheTransfermodetobeporterduffanddestinationin
paint.setXfermode(newPorterDuffXfermode(Mode.DST_IN));
//Drawarectangleusingthepaintwithourlineargradient
canvas.drawRect(0,height,width,
bitmapWithReflection.getHeight()+reflectionGap,paint);
ImageViewimageView=newImageView(mContext);
imageView.setImageBitmap(bitmapWithReflection);
imageView
.setLayoutParams(newGalleryFlow.LayoutParams(160,240));
//imageView.setScaleType(ScaleType.MATRIX);
mImages[index++]=imageView;
}
returntrue;
}
publicintgetCount(){
returnmImageIds.length;
}
publicObjectgetItem(intposition){
returnposition;
}
publiclonggetItemId(intposition){
returnposition;
}
publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
//Usethiscodeifyouwanttoloadfromresources
/*
*ImageViewi=newImageView(mContext);
*i.setImageResource(mImageIds[position]);i.setLayoutParams(new
*CoverFlow.LayoutParams(350,350));
*i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
*
*//Makesurewesetanti-aliasingotherwisewegetjaggies
*BitmapDrawabledrawable=(BitmapDrawable)i.getDrawable();
*drawable.setAntiAlias(true);returni;
*/
returnmImages[position];
}
/**
*Returnsthesize(0.0fto1.0f)oftheviewsdependingonthe
*'offset'tothecenter.
*/
publicfloatgetScale(booleanfocused,intoffset){
/*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用于视图变换。具体可参考代码注释。
publicclassGalleryFlowextendsGallery{
/**
*GraphicsCamerausedfortransformingthematrixofImageViews
*/
privateCameramCamera=newCamera();
/**
*ThemaximumangletheChildImageViewwillberotatedby
*/
privateintmMaxRotationAngle=60;
/**
*ThemaximumzoomonthecentreChild
*/
privateintmMaxZoom=-120;
/**
*TheCentreoftheCoverflow
*/
privateintmCoveflowCenter;
publicGalleryFlow(Contextcontext){
super(context);
this.setStaticTransformationsEnabled(true);
}
publicGalleryFlow(Contextcontext,AttributeSetattrs){
super(context,attrs);
this.setStaticTransformationsEnabled(true);
}
publicGalleryFlow(Contextcontext,AttributeSetattrs,intdefStyle){
super(context,attrs,defStyle);
this.setStaticTransformationsEnabled(true);
}
/**
*Getthemaxrotationalangleoftheimage
*
*@returnthemMaxRotationAngle
*/
publicintgetMaxRotationAngle(){
returnmMaxRotationAngle;
}
/**
*Setthemaxrotationalangleofeachimage
*
*@parammaxRotationAngle
*themMaxRotationAngletoset
*/
publicvoidsetMaxRotationAngle(intmaxRotationAngle){
mMaxRotationAngle=maxRotationAngle;
}
/**
*GettheMaxzoomofthecentreimage
*
*@returnthemMaxZoom
*/
publicintgetMaxZoom(){
returnmMaxZoom;
}
/**
*Setthemaxzoomofthecentreimage
*
*@parammaxZoom
*themMaxZoomtoset
*/
publicvoidsetMaxZoom(intmaxZoom){
mMaxZoom=maxZoom;
}
/**
*GettheCentreoftheCoverflow
*
*@returnThecentreofthisCoverflow.
*/
privateintgetCenterOfCoverflow(){
return(getWidth()-getPaddingLeft()-getPaddingRight())/2
+getPaddingLeft();
}
/**
*GettheCentreoftheView
*
*@returnThecentreofthegivenview.
*/
privatestaticintgetCenterOfView(Viewview){
returnview.getLeft()+view.getWidth()/2;
}
/**
*{@inheritDoc}
*
*@see#setStaticTransformationsEnabled(boolean)
*/
protectedbooleangetChildStaticTransformation(Viewchild,Transformationt){
finalintchildCenter=getCenterOfView(child);
finalintchildWidth=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;
}
/**
*Thisiscalledduringlayoutwhenthesizeofthisviewhaschanged.If
*youwerejustaddedtotheviewhierarchy,you'recalledwiththeold
*valuesof0.
*
*@paramw
*Currentwidthofthisview.
*@paramh
*Currentheightofthisview.
*@paramoldw
*Oldwidthofthisview.
*@paramoldh
*Oldheightofthisview.
*/
protectedvoidonSizeChanged(intw,inth,intoldw,intoldh){
mCoveflowCenter=getCenterOfCoverflow();
super.onSizeChanged(w,h,oldw,oldh);
}
/**
*TransformtheImageBitmapbytheAnglepassed
*
*@paramimageView
*ImageViewtheImageViewwhosebitmapwewanttorotate
*@paramt
*transformation
*@paramrotationAngle
*theAnglebywhichtorotatetheBitmap
*/
privatevoidtransformImageBitmap(ImageViewchild,Transformationt,
introtationAngle){
mCamera.save();
finalMatriximageMatrix=t.getMatrix();
finalintimageHeight=child.getLayoutParams().height;
finalintimageWidth=child.getLayoutParams().width;
finalintrotation=Math.abs(rotationAngle);
//在Z轴上正向移动camera的视角,实际效果为放大图片。
//如果在Y轴上移动,则图片上下移动;X轴上对应图片左右移动。
mCamera.translate(0.0f,0.0f,100.0f);
//Astheangleoftheviewgetsless,zoomin
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();
}
}
代码到这里就结束了。有兴趣的话可以自行调整里面的参数来实现更多更炫的效果。
下面是调用的示例:
publicvoidonCreate(BundlesavedInstanceState){
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};
ImageAdapteradapter=newImageAdapter(this,images);
adapter.createReflectedImages();
GalleryFlowgalleryFlow=(GalleryFlow)findViewById(R.id.gallery_flow);
galleryFlow.setAdapter(adapter);
}
PS1:
可以看出来这样实现的gallery锯齿问题比较严重。可以在createReflectedImages()使用以下代码:
BitmapDrawablebd=newBitmapDrawable(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~
PS3ONPS1:
为什么开启抗锯齿后不明显。答案是,锯齿不可能完全消除,但开启抗锯齿后会有很大改善。
另外还说到为什么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执行后对图像本身不会有影响,影响的是对图像进行变换时的旋转轴。
说了这么多有点绕,其实就是矩阵变换的知识。
PS5ONPS2:
这个问题在googlegroup下有过很充分的讨论,貌似一般只在debug模式下存在。现在我使用这段代码没有出现OOM问题了
希望本文所述对大家Android程序设计有所帮助。