Android实现网络加载图片点击大图后浏览可缩放
本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下
找了一些demo感觉没有自己想要的效果,于是借鉴一些改造一下并记录下来;
1、主Activity
publicclassPictureViewFraextendsActivity{ privatePicGallerygallery; //privateViewGrouptweetLayout;//弹层 privatebooleanmTweetShow=false;//弹层是否显示 //屏幕宽度 publicstaticintscreenWidth; //屏幕高度 publicstaticintscreenHeight; privateGalleryAdaptermAdapter; privateArrayListhelpTopicImage=newArrayList (); privateintposition=0; //privateProgressDialogmProgress; privateTextViewtv_img_count,tv_topic_title; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.picture_view); getIntentData(); tv_img_count=(TextView)findViewById(R.id.tv_img_count); tv_topic_title=(TextView)findViewById(R.id.tv_topic_title); gallery=(PicGallery)findViewById(R.id.pic_gallery); gallery.setVerticalFadingEdgeEnabled(false);//取消竖直渐变边框 gallery.setHorizontalFadingEdgeEnabled(false);//取消水平渐变边框 gallery.setDetector(newGestureDetector(this, newMySimpleGesture())); mAdapter=newGalleryAdapter(this,helpTopicImage,position); gallery.setAdapter(mAdapter); gallery.setOnItemLongClickListener(newOnItemLongClickListener(){ @Override publicbooleanonItemLongClick(AdapterView>arg0,Viewarg1,intarg2,longarg3){ returnfalse; } }); mAdapter.getPositionListener(newGalleryAdapter.GalleryPositionListener(){ @Override publicvoidmovePosition(intindex){ Log.d("helpTopicImage-->",""+index); tv_img_count.setText((index+1)+"/"+helpTopicImage.size()); tv_topic_title.setText(helpTopicImage.get(index).getImgInfo()); } }); //mAdapter.setData(dataResult); initViews(); //mProgress=ProgressDialog.show(getActivity(), //null,getActivity().getString(R.string.loading)); } privatevoidgetIntentData(){ Intentintent=getIntent(); helpTopicImage=(ArrayList )intent.getSerializableExtra("helpTopicImage"); position=intent.getIntExtra("position",0); } privatevoidinitViews(){ screenWidth=getWindow().getWindowManager().getDefaultDisplay() .getWidth(); screenHeight=getWindow().getWindowManager().getDefaultDisplay() .getHeight(); } privateclassMySimpleGestureextendsSimpleOnGestureListener{ //按两下的第二下Touchdown时触发 publicbooleanonDoubleTap(MotionEvente){ Viewview=gallery.getSelectedView(); if(viewinstanceofMyImageView){ MyImageViewimageView=(MyImageView)view; if(imageView.getScale()>imageView.getMiniZoom()){ imageView.zoomTo(imageView.getMiniZoom()); }else{ imageView.zoomTo(imageView.getMaxZoom()); } }else{ } returntrue; } @Override publicbooleanonSingleTapConfirmed(MotionEvente){ //Logger.LOG("onSingleTapConfirmed", //"onSingleTapConfirmedexcute"); //mTweetShow=!mTweetShow; //tweetLayout.setVisibility(mTweetShow?View.VISIBLE //:View.INVISIBLE); returntrue; } } }
2、显示图片的GalleryAdapter
publicclassGalleryAdapterextendsBaseAdapter{ privateContextcontext; privateArrayListimageViews=newArrayList (); privateGalleryPositionListenerpositionListener; privateArrayList helpTopicImage=newArrayList (); privateintposition=0; privateArrayList bitmaps=newArrayList (); privateHandlerhandler=newHandler(){ publicvoidhandleMessage(Messagemsg){ Bitmapbitmap=(Bitmap)msg.obj; Bundlebundle=msg.getData(); Stringurl=bundle.getString("url"); for(inti=0;i data){ notifyDataSetChanged(); } publicGalleryAdapter(Contextcontext,ArrayList helpTopicImage,intposition){ this.context=context; this.helpTopicImage=helpTopicImage; this.position=position; for(inti=0;i 3、自定义的Gallery
publicclassPicGalleryextendsGallery{ privateGestureDetectorgestureScanner; privateMyImageViewimageView; publicPicGallery(Contextcontext){ super(context); } publicPicGallery(Contextcontext,AttributeSetattrs,intdefStyle){ super(context,attrs,defStyle); } publicvoidsetDetector(GestureDetectordectector){ gestureScanner=dectector; } publicPicGallery(Contextcontext,AttributeSetattrs){ super(context,attrs); this.setOnTouchListener(newOnTouchListener(){ floatbaseValue; floatoriginalScale; @Override publicbooleanonTouch(Viewv,MotionEventevent){ Viewview=PicGallery.this.getSelectedView(); if(viewinstanceofMyImageView){ imageView=(MyImageView)view; if(event.getAction()==MotionEvent.ACTION_DOWN){ baseValue=0; originalScale=imageView.getScale(); } if(event.getAction()==MotionEvent.ACTION_MOVE){ if(event.getPointerCount()==2){ floatx=event.getX(0)-event.getX(1); floaty=event.getY(0)-event.getY(1); floatvalue=(float)Math.sqrt(x*x+y*y);//计算两点的距离 //System.out.println("value:"+value); if(baseValue==0){ baseValue=value; }else{ floatscale=value/baseValue;//当前两点间的距离除以手指落下时两点间的距离就是需要缩放的比例。 //scaletheimage imageView.zoomTo(originalScale*scale,x +event.getX(1),y+event.getY(1)); } } } } returnfalse; } }); } floatv[]=newfloat[9]; @Override publicbooleanonScroll(MotionEvente1,MotionEvente2,floatdistanceX, floatdistanceY){ Viewview=PicGallery.this.getSelectedView(); if(viewinstanceofMyImageView){ floatxdistance=calXdistance(e1,e2); floatmin_distance=PictureViewFra.screenWidth/4f; if(isScrollingLeft(e1,e2)&&xdistance>min_distance){ kEvent=KeyEvent.KEYCODE_DPAD_LEFT; }elseif(!isScrollingLeft(e1,e2)&&xdistance>min_distance){ kEvent=KeyEvent.KEYCODE_DPAD_RIGHT; } imageView=(MyImageView)view; Matrixm=imageView.getImageMatrix(); m.getValues(v); //图片实时的上下左右坐标 floatleft,right; //图片的实时宽,高 floatwidth=imageView.getScale()*imageView.getImageWidth(); floatheight=imageView.getScale()*imageView.getImageHeight(); if((int)width<=PictureViewFra.screenWidth &&(int)height<=PictureViewFra.screenHeight)//如果图片当前大小<屏幕大小,直接处理滑屏事件 { super.onScroll(e1,e2,distanceX,distanceY); }else{ left=v[Matrix.MTRANS_X]; right=left+width; Rectr=newRect(); imageView.getGlobalVisibleRect(r); if(distanceX>0)//向左滑动 { if(r.left>0||right0){ super.onScroll(e1,e2,distanceX,distanceY); }else{ imageView.postTranslate(-distanceX,-distanceY); } } } }else{ super.onScroll(e1,e2,distanceX,distanceY); } returnfalse; } privatebooleanisScrollingLeft(MotionEvente1,MotionEvente2){ returne2.getX()>e1.getX(); } privatefloatcalXdistance(MotionEvente1,MotionEvente2){ returnMath.abs(e2.getX()-e1.getX()); } @Override publicbooleanonFling(MotionEvente1,MotionEvente2,floatvelocityX, floatvelocityY){ returnfalse; } @Override publicbooleanonTouchEvent(MotionEventevent){ //Logger.d(DEBUG,"[PicGallery.onTouchEvent]"+"PicGallery.onTouchEvent"); if(gestureScanner!=null){ gestureScanner.onTouchEvent(event); } switch(event.getAction()){ caseMotionEvent.ACTION_UP: //判断边界是否越界 Viewview=PicGallery.this.getSelectedView(); if(viewinstanceofMyImageView){ if(kEvent!=KEY_INVALID){//是否切换上一页或下一页 onKeyDown(kEvent,null); kEvent=KEY_INVALID; } imageView=(MyImageView)view; floatwidth=imageView.getScale()*imageView.getImageWidth(); floatheight=imageView.getScale() *imageView.getImageHeight(); //Logger.LOG("onTouchEvent","width="+width+",height=" //+height+",screenWidth=" //+PictureViewActivity.screenWidth+",screenHeight=" //+PictureViewActivity.screenHeight); if((int)width<=PictureViewFra.screenWidth &&(int)height<=PictureViewFra.screenHeight)//如果图片当前大小<屏幕大小,判断边界 { break; } floatv[]=newfloat[9]; Matrixm=imageView.getImageMatrix(); m.getValues(v); floattop=v[Matrix.MTRANS_Y]; floatbottom=top+height; if(top<0&&bottom 0&&bottom>PictureViewFra.screenHeight){ //imageView.postTranslateDur(PictureViewActivity.screenHeight //-bottom,200f); imageView.postTranslateDur(-top,200f); } floatleft=v[Matrix.MTRANS_X]; floatright=left+width; if(left<0&&right 0&&right>PictureViewFra.screenWidth){ //imageView.postTranslateXDur(PictureViewActivity.screenWidth //-right,200f); imageView.postTranslateXDur(-left,200f); } } break; } returnsuper.onTouchEvent(event); } intkEvent=KEY_INVALID;//invalid publicstaticfinalintKEY_INVALID=-1; } 4、自定义的ImageView
publicclassMyImageViewextendsImageView{ //Thisisthebasetransformationwhichisusedtoshowtheimage //initially.Thecurrentcomputationforthisshowstheimagein //it'sentirety,letterboxingasneeded.Onecouldchooseto //showtheimageascroppedinstead. // //Thismatrixisrecomputedwhenwegofromthethumbnailimageto //thefullsizeimage. protectedMatrixmBaseMatrix=newMatrix(); //Thisisthesupplementarytransformationwhichreflectswhat //theuserhasdoneintermsofzoomingandpanning. // //Thismatrixremainsthesamewhenwegofromthethumbnailimage //tothefullsizeimage. protectedMatrixmSuppMatrix=newMatrix(); //Thisisthefinalmatrixwhichiscomputedastheconcatentation //ofthebasematrixandthesupplementarymatrix. privatefinalMatrixmDisplayMatrix=newMatrix(); //Temporarybufferusedforgettingthevaluesoutofamatrix. privatefinalfloat[]mMatrixValues=newfloat[9]; //Thecurrentbitmapbeingdisplayed. protectedBitmapimage=null; protectedHandlermHandler=newHandler(); intmThisWidth=-1,mThisHeight=-1;//布局后的宽度和高度,由于是全屏显示,这两个值等于屏幕分辨率 floatmMaxZoom;//最大缩放比例 floatmMinZoom;//最小缩放比例 privateintimageWidth;//图片的原始宽度 privateintimageHeight;//图片的原始高度 //floatscaleRate;//图片适应屏幕的缩放比例 staticfinalfloatSCALE_RATE=1.25F; publicMyImageView(Contextcontext,AttributeSetattrs){ super(context,attrs); init(); } publicMyImageView(Contextcontext){ super(context); init(); } @Override publicvoidsetImageBitmap(Bitmapbitmap){ super.setImageBitmap(bitmap); image=bitmap; setImageHeight(bitmap.getHeight()); setImageWidth(bitmap.getWidth()); Drawabled=getDrawable(); if(d!=null){ d.setDither(true); } } //Centerasmuchaspossibleinoneorbothaxis.Centeringis //definedasfollows:iftheimageisscaleddownbelowthe //view'sdimensionsthencenterit(literally).Iftheimage //isscaledlargerthantheviewandistranslatedoutofview //thentranslateitbackintoview(i.e.eliminateblackbars). protectedvoidcenter(booleanhorizontal,booleanvertical){ if(image==null){ return; } Matrixm=getImageViewMatrix(); RectFrect=newRectF(0,0,image.getWidth(),image.getHeight()); //RectFrect=newRectF(0,0,imageWidth*getScale(), //imageHeight*getScale()); m.mapRect(rect); floatheight=rect.height(); floatwidth=rect.width(); floatdeltaX=0,deltaY=0; if(vertical){ intviewHeight=getHeight(); if(height0){ deltaY=-rect.top; }elseif(rect.bottom 0){ deltaX=-rect.left; }elseif(rect.right mMaxZoom){ scale=mMaxZoom; }elseif(scale =mMaxZoom){ return;//Don'tlettheuserzoomintothemolecularlevel. } if(image==null){ return; } floatcx=getWidth()/2F; floatcy=getHeight()/2F; mSuppMatrix.postScale(rate,rate,cx,cy); setImageMatrix(getImageViewMatrix()); } protectedvoidzoomOut(floatrate){ if(image==null){ return; } floatcx=getWidth()/2F; floatcy=getHeight()/2F; //Zoomouttoatmost1x. Matrixtmp=newMatrix(mSuppMatrix); tmp.postScale(1F/rate,1F/rate,cx,cy); if(getScale(tmp)<1F){ mSuppMatrix.setScale(1F,1F,cx,cy); }else{ mSuppMatrix.postScale(1F/rate,1F/rate,cx,cy); } setImageMatrix(getImageViewMatrix()); center(true,true); } publicvoidpostTranslate(floatdx,floatdy){ mSuppMatrix.postTranslate(dx,dy); setImageMatrix(getImageViewMatrix()); } float_dy=0.0f; protectedvoidpostTranslateDur(finalfloatdy,finalfloatdurationMs){ _dy=0.0f; finalfloatincrementPerMs=dy/durationMs; finallongstartTime=System.currentTimeMillis(); mHandler.post(newRunnable(){ publicvoidrun(){ longnow=System.currentTimeMillis(); floatcurrentMs=Math.min(durationMs,now-startTime); postTranslate(0,incrementPerMs*currentMs-_dy); _dy=incrementPerMs*currentMs; if(currentMs mMinZoom){ zoomTo(mMinZoom); returntrue; } } returnsuper.onKeyUp(keyCode,event); } publicintgetImageWidth(){ returnimageWidth; } publicvoidsetImageWidth(intimageWidth){ this.imageWidth=imageWidth; } publicintgetImageHeight(){ returnimageHeight; } publicvoidsetImageHeight(intimageHeight){ this.imageHeight=imageHeight; } } 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。