欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2024-03-07 15:07:03
本文实例讲述了android实现动态向gallery中添加图片及倒影与3d效果的方法。分享给大家供大家参考,具体如下: 在android中gallery可以提供一个很...

本文实例讲述了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, t, 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 in
if (rotation < mmaxrotationangle) {
float zoomamount = (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();
 }
}

在布局文件中

<?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"
>
<linearlayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:orientation="vertical" android:paddingtop="10px"
>
<linearlayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:orientation="horizontal"
>
<textview
android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:id="@+id/dishname"   android:textsize="18pt"
 android:text="菜名"
/>
<linearlayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:orientation="horizontal" android:paddingleft="10px"
>
<textview
android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:id="@+id/ds"   android:textsize="18pt"
 android:text="评分 : "
/>
<ratingbar
android: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" style="?android:attr/ratingbarstylesmall"
/>
</linearlayout>
</linearlayout>
<linearlayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:orientation="horizontal"
>
<textview
android:layout_width="fill_parent" android:layout_height="wrap_content"
 android:id="@+id/dishprice" android:text="价格" android:textsize="18pt"
/>
</linearlayout>
</linearlayout>
<nate.android.service.mygallery
android:id="@+id/gallery01"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_centerinparent="true"
/>
<textview
android: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), 0, 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, 0,
     height /2, width, height /2, matrix, false);
   bitmap bitmapwithreflection = bitmap.createbitmap(width,
     (height + height /2), config.argb_8888);
   canvas canvas =new canvas(bitmapwithreflection);
   canvas.drawbitmap(originalimage, 0, 0, null);
   paint deafaultpaint =new paint();
   canvas.drawrect(0, height, width, height + reflectiongap,
     deafaultpaint);
   canvas.drawbitmap(reflectionimage, 0, height + reflectiongap, null);
   paint paint =new paint();
   lineargradient shader =new lineargradient(0, originalimage
     .getheight(), 0, bitmapwithreflection.getheight()
+ reflectiongap, 0x70ffffff, 0x00ffffff, tilemode.clamp);
   paint.setshader(shader);
   paint.setxfermode(new porterduffxfermode(mode.dst_in));
   canvas.drawrect(0, height, width, bitmapwithreflection.getheight()
+ reflectiongap, 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), 0, dishimages.get(i).length);

在这篇文章有较详细的说明:

将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(){
  @override
publicvoid handlemessage(message msg) {
   loadingdialog.dismiss();
//other operation
super.handlemessage(msg);
  }
 };
/**
  * thread to load the data from local database or from the server
  * @author administrator
  *
*/
class loading implements runnable{
  @override
publicvoid 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();
//初始化 dishimages
for(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(){
   @override
publicvoid 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");
   }
   @override
publicvoid onnothingselected(adapterview<?> arg0) {
   }
  });
  galleryflow.setonitemclicklistener(new onitemclicklistener(){
  @override
publicvoid onitemclick(adapterview<?> arg0, view arg1, int arg2,
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程序设计有所帮助。