Android实现动态向Gallery中添加图片及倒影与3D效果示例

Android实现动态向Gallery中添加图片及倒影与3D效果示例,第1张

概述本文实例讲述了Android实现动态向Gallery中添加图片及倒影与3D效果的方法。分享给大家供大家参考,具体如下:

本文实例讲述了AndroID实现动态向gallery中添加图片及倒影与3D效果的方法。分享给大家供大家参考,具体如下:

在AndroID中gallery可以提供一个很好的显示图片的方式,实现上面的效果以及动态添加数据库或者网络上下载下来的图片资源。我们首先实现一个自定义的gallery类。

Mygallery.java:

package nate.androID.Service;import androID.content.Context;import androID.graphics.Camera;import androID.graphics.Matrix;import androID.graphics.Rect;import androID.util.AttributeSet;import androID.vIEw.VIEw;import androID.vIEw.animation.transformation;import androID.Widget.gallery;import androID.Widget.ImageVIEw;import androID.Widget.Toast;publicclass Mygallery extends gallery {private Camera mCamera =new Camera();privateint mMaxRotationAngle =45;privateint mMaxZoom =-120;privateint mCoveflowCenter;public Mygallery(Context context) {super(context);this.setStatictransformationsEnabled(true); }public Mygallery(Context context,AttributeSet attrs) {super(context,attrs);this.setStatictransformationsEnabled(true); }public Mygallery(Context context,AttributeSet attrs,int defStyle) {super(context,attrs,defStyle);this.setStatictransformationsEnabled(true); }publicint getMaxRotationAngle() {return mMaxRotationAngle; }publicvoID setMaxRotationAngle(int maxRotationAngle) {   mMaxRotationAngle = maxRotationAngle; }publicint getMaxZoom() {return mMaxZoom; }publicvoID setMaxZoom(int maxZoom) {   mMaxZoom = maxZoom; }privateint getCenterOfCoverflow() {return (getWIDth() - getpaddingleft() - getpaddingRight()) /2+ getpaddingleft(); }privatestaticint getCenterOfVIEw(VIEw vIEw) {return vIEw.getleft() + vIEw.getWIDth() /2; }protectedboolean getChildStatictransformation(VIEw child,transformation t) {finalint childCenter = getCenterOfVIEw(child);finalint chilDWIDth = child.getWIDth();int rotationAngle =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,rotationAngle);   }returntrue; }protectedvoID onSizeChanged(int w,int h,int olDW,int oldh) {   mCoveflowCenter = getCenterOfCoverflow();super.onSizeChanged(w,h,olDW,oldh); }privatevoID transformImageBitmap(ImageVIEw child,transformation t,int rotationAngle) {   mCamera.save();final Matrix 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 inif (rotation < mMaxRotationAngle) {float zoomAmount = (float) (mMaxZoom + (rotation *1.5));     mCamera.translate(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(); }}

在布局文件中

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:orIEntation="vertical" androID:layout_wIDth="fill_parent" androID:layout_height="fill_parent" androID:background="#ffffff"><linearLayoutandroID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="vertical" androID:paddingtop="10px"><linearLayoutandroID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal"><TextVIEwandroID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:ID="@+ID/dishname"   androID:textSize="18pt" androID:text="菜名"/><linearLayoutandroID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal" androID:paddingleft="10px"><TextVIEwandroID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:ID="@+ID/ds"   androID:textSize="18pt" androID:text="评分 : "/><ratingbarandroID:numStars="5" androID:rating="3" androID:stepSize="0.2" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:isIndicator="true" androID:ID="@+ID/dishscores" /></linearLayout></linearLayout><linearLayoutandroID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal"><TextVIEwandroID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:ID="@+ID/dishPrice" androID:text="价格" androID:textSize="18pt"/></linearLayout></linearLayout><nate.androID.Service.MygalleryandroID:ID="@+ID/gallery01" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:layout_centerInParent="true"/><TextVIEwandroID:text="\n\n\n\n这里是关于每一道菜的信息,点击图片进入评论" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:layout_below="@+ID/gallery01" androID:paddingleft="5px" androID:ID="@+ID/showHint"/></linearLayout>

在上面的XML文件中,我们使用了自定义的Mygallery。

然后顶一个ImageAdapter类继承自BaseAdapter。

package nate.androID.Service;import java.util.ArrayList;import androID.content.Context;import androID.content.res.Resources;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.graphics.Canvas;import androID.graphics.linearGradIEnt;import androID.graphics.Matrix;import androID.graphics.Paint;import androID.graphics.PorterDuffXfermode;import androID.graphics.Bitmap.Config;import androID.graphics.PorterDuff.Mode;import androID.graphics.Shader.TileMode;import androID.vIEw.VIEw;import androID.vIEw.VIEwGroup;import androID.Widget.BaseAdapter;import androID.Widget.ImageVIEw;publicclass ImageAdapter extends BaseAdapter {int mgalleryItemBackground;private Context mContext;private ArrayList<byte[]> dishImages =new ArrayList<byte[]>();private ImageVIEw[] mImages;public ImageAdapter(Context c,ArrayList<byte[]> tmpdishImages) {  mContext = c;  dishImages = tmpdishImages;  mImages =new ImageVIEw[dishImages.size()]; }publicboolean createReflectedImages() {finalint reflectionGap =4;int index =0;  System.out.println("dishImages size "+ dishImages.size());for (int i =0; i < dishImages.size(); ++i ) {   System.out.println("dishImage --- "+ dishImages.get(i));   Bitmap originalimage = BitmapFactory.decodeByteArray(dishImages.get(i),dishImages.get(i).length);int wIDth = originalimage.getWIDth();int height = originalimage.getHeight();   Matrix matrix =new Matrix();   matrix.preScale(1,-1);   Bitmap reflectionImage = Bitmap.createBitmap(originalimage,height /2,wIDth,matrix,false);   Bitmap bitmapWithreflection = Bitmap.createBitmap(wIDth,(height + height /2),Config.ARGB_8888);   Canvas canvas =new Canvas(bitmapWithreflection);   canvas.drawBitmap(originalimage,null);   Paint deafaultPaint =new Paint();   canvas.drawRect(0,height,height + reflectionGap,deafaultPaint);   canvas.drawBitmap(reflectionImage,null);   Paint paint =new Paint();   linearGradIEnt shader =new linearGradIEnt(0,originalimage     .getHeight(),bitmapWithreflection.getHeight()+ reflectionGap,0x70ffffff,0x00ffffff,TileMode.CLAMP);   paint.setShader(shader);   paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));   canvas.drawRect(0,paint);   ImageVIEw imageVIEw =new ImageVIEw(mContext);   imageVIEw.setimageBitmap(bitmapWithreflection);//   imageVIEw.setLayoutParams(new galleryFlow.LayoutParams(180,240));   imageVIEw.setLayoutParams(new Mygallery.LayoutParams(270,360));//imageVIEw.setScaleType(ScaleType.MATRIX);   mImages[index++] = imageVIEw;  }returntrue; }private Resources getResources() {returnnull; }publicint getCount() {return dishImages.size(); }public Object getItem(int position) {return position; }publiclong getItemID(int position) {return position; }public VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) {return mImages[position]; }publicfloat getScale(boolean focused,int offset) {return Math.max(0,1.0f/ (float) Math.pow(2,Math.abs(offset))); }}

在这个类中构造函数需要传入将要在gallery中绘制的图片数据,(以byte[]类型的为例,因为我在存入sqlite以及从从网络下载下来的图片demo中都将其转成byte[]),同样我们使用

复制代码 代码如下:Bitmap originalimage = BitmapFactory.decodeByteArray(dishImages.get(i),dishImages.get(i).length);

在这篇文章有较详细的说明:https://www.oudahe.com/p/28335/

将byte[]类型的图片数据“还原”。byte[]类型的图片源数据保存在一个ArrayList<byte[]>当中。这样我们为动态的实现在gallery中添加图片提供数据来源。

在下面的activity中使用我们自定义的baseAdapter以及gallery。实现上图显示的效果。

使用实例类

package com.nate.wte2;import java.io.IOException;import java.util.ArrayList;import nate.InfoService.dishInfo;import nate.InfoService.StoreInfoService;import nate.InfoService.WhichChoice;import nate.NetConnection.GetConnectionSock;import nate.androID.Service.galleryFlow;import nate.androID.Service.ImageAdapter;import androID.app.Activity;import androID.app.ProgressDialog;import androID.content.Intent;import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.vIEw.VIEw;import androID.Widget.AdapterVIEw;import androID.Widget.ratingbar;import androID.Widget.TextVIEw;import androID.Widget.Toast;import androID.Widget.AdapterVIEw.OnItemClickListener;import androID.Widget.AdapterVIEw.OnItemSelectedListener;import com.nate.wte.Localsql.StoresInfoDB;publicclass dishMenuActivity extends Activity {private ArrayList<dishInfo> dishInfoList =new ArrayList<dishInfo>();private TextVIEw dishname;private ratingbar dishscores;private TextVIEw dishPrice;//3:send the dish's whole info to fill the activity(send the comments of the dish)privateint flag3 =3; WhichChoice choice3 =new WhichChoice(flag3);private StoreInfoService storeInfo;private ProgressDialog loadingDialog;/**  * handler handle the dialog dismission*/private Handler handler =new Handler(){  @OverrIDepublicvoID handleMessage(Message msg) {   loadingDialog.dismiss();//other operationsuper.handleMessage(msg);  } };/**  * thread to load the data from local database or from the server  * @author administrator  **/class Loading implements Runnable{  @OverrIDepublicvoID run() {try {//这儿的sleep将换成一个循环,知道某个条件满足时候才结束循环,让dialog终止    Thread.sleep(1500);    handler.sendEmptyMessage(0);   } catch (InterruptedException e) {    e.printstacktrace();   }  } }/**  * loading the items,start the thread to load*/publicvoID loadingItems(){  loadingDialog = ProgressDialog.show(dishMenuActivity.this,"","loading...");  Thread t =new Thread(new Loading());  t.start(); }publicvoID onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);  setContentVIEw(R.layout.dishmenu_gallery);  StoresInfoDB infoDB;int dishInfoListLength;  ArrayList<byte[]> dishImages =new ArrayList<byte[]>();byte[] dishImage;  dishname = (TextVIEw)this.findVIEwByID(R.ID.dishname);  dishPrice = (TextVIEw)this.findVIEwByID(R.ID.dishPrice);  dishscores = (ratingbar)this.findVIEwByID(R.ID.dishscores);//得到intent中从Choices类中传过来的对象  Intent intent = getIntent();  Bundle bundle = intent.getBundleExtra("bundleData");  storeInfo = (StoreInfoService)bundle.getSerializable("storeInfo");  dishInfoList = (ArrayList<dishInfo>)bundle.getSerializable("dishInfoList");  System.out.println("look look the info received from Choices Activity");for(int i =0; i < dishInfoList.size(); i++){   System.out.println("--- "+ i + dishInfoList.get(i).getdishImage().toString());  }  dishInfoListLength = dishInfoList.size();//初始化 dishImagesfor(int i =0; i < dishInfoListLength; i++){   dishImages.add(dishInfoList.get(i).getdishImage());  }  System.out.println("the length of the dishImages ---- "+ dishImages.size());//////////////////////////////////注意这里一段////////////////////////////////  ImageAdapter adapter =new ImageAdapter(dishMenuActivity.this,dishImages);  adapter.createReflectedImages();  galleryFlow galleryFlow = (galleryFlow) findVIEwByID(R.ID.gallery01);  galleryFlow.setonItemSelectedListener(new OnItemSelectedListener(){   @OverrIDepublicvoID onItemSelected(AdapterVIEw<?> arg0,VIEw arg1,int arg2,long arg3) {    String showname ="菜名 : "+ dishInfoList.get((int)arg3).getdishname() +"";    dishname.setText(showname);    dishscores.setrating(dishInfoList.get((int)arg3).getdishscores());    dishPrice.setText("价格 : "+ dishInfoList.get((int)arg3).getPrice() +" 元\n\n\n");   }   @OverrIDepublicvoID onnothingSelected(AdapterVIEw<?> arg0) {   }  });  galleryFlow.setonItemClickListener(new OnItemClickListener(){  @OverrIDepublicvoID onItemClick(AdapterVIEw<?> arg0,long arg3) {   loadingItems();   dishInfo dishInfo = dishInfoList.get((int)arg3);try {    GetConnectionSock.fromClIEnt.writeObject(choice3);    System.out.println("send the flag 3 ");    GetConnectionSock.fromClIEnt.writeObject(dishInfo);    System.out.println("send the name back to server");    dishInfo dishComments = (dishInfo)GetConnectionSock.fromServer.readobject();    System.out.println("recv the dish comments");    dishInfo.setdishname(dishInfoList.get((int)arg3).getdishname());    dishInfo.setdishComments(dishComments.getdishComments());    System.out.println("full the dish info");   } catch (IOException e) {    e.printstacktrace();   } catch (ClassNotFoundException e) {    e.printstacktrace();   }   Intent intent =new Intent();   Bundle bundle =new Bundle();   bundle.putSerializable("dishInfo",dishInfo);   bundle.putSerializable("storeInfo",storeInfo);   intent.putExtra("dishBundleData",bundle);   intent.setClass(dishMenuActivity.this,dishInfoDynamic.class);   Toast.makeText(dishMenuActivity.this,"进入评论此道菜",Toast.LENGTH_LONG).show();   dishMenuActivity.this.startActivity(intent);  }  });  galleryFlow.setAdapter(adapter); //注意这里 }}

在这个activity中跟本文相关的,也就是在galley中添加图片功能,只需注意上面代码中标注出来的部分代码即可,至于数据来源得到的方式都不一样,这里只要知道数据是一个ArrayList<byte[]>就行了。重要的是利用上面的Mygallery以及ImageAdapter,当然,通过简单的理解,很轻松的这两个类就能够在其他的工程中重用的

更多关于AndroID相关内容感兴趣的读者可查看本站专题:《Android图形与图像处理技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android多媒体 *** 作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家AndroID程序设计有所帮助。

总结

以上是内存溢出为你收集整理的Android实现动态向Gallery中添加图片及倒影与3D效果示例全部内容,希望文章能够帮你解决Android实现动态向Gallery中添加图片及倒影与3D效果示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1148637.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存