android 实现倒影

首先,文章中出现的Gallery 已经不再适用,替代方法请看我的另一篇文章http://blog.csdn.net/xiangzhihong8/article/details/51120460

不过对于文章中说的倒影的原理是可以借鉴的。


1.图片的显示以及切换主要是自定义了一个Gallery

下面是代码myGallery.java:

[java]  view plain  copy
 print ?
  1. import android.content.Context;  
  2. import android.graphics.Camera;  
  3. import android.graphics.Matrix;  
  4. import android.util.AttributeSet;  
  5. import android.view.View;  
  6. import android.view.animation.Transformation;  
  7. import android.widget.Gallery;  
  8. import android.widget.ImageView;  
  9.   
  10. @SuppressWarnings("deprecation")  
  11. public class myGallery extends Gallery {  
  12.   
  13.     private Camera mCamera = new Camera();  
  14.     private int mMaxRotationAngle = 60;     //图片偏转角度 60  
  15.     private int mMaxZoom = -120;  
  16.     private int mCoveflowCenter;  
  17.   
  18.     public myGallery(Context context) {  
  19.         super(context);  
  20.         this.setStaticTransformationsEnabled(true);  
  21.     }  
  22.   
  23.     public myGallery(Context context, AttributeSet attrs) {  
  24.         super(context, attrs);  
  25.         this.setStaticTransformationsEnabled(true);  
  26.     }  
  27.   
  28.     public myGallery(Context context, AttributeSet attrs, int defStyle) {  
  29.         super(context, attrs, defStyle);  
  30.         this.setStaticTransformationsEnabled(true);  
  31.     }  
  32.   
  33.     public int getMaxRotationAngle() {  
  34.         return mMaxRotationAngle;  
  35.     }  
  36.   
  37.     public void setMaxRotationAngle(int maxRotationAngle) {  
  38.         mMaxRotationAngle = maxRotationAngle;  
  39.     }  
  40.   
  41.     public int getMaxZoom() {  
  42.         return mMaxZoom;  
  43.     }  
  44.   
  45.     public void setMaxZoom(int maxZoom) {  
  46.         mMaxZoom = maxZoom;  
  47.     }  
  48.   
  49.     /** 获得Gallery中心到边界的距离*/  
  50.     private int getCenterOfCoverflow() {  
  51.         return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft();  
  52.     }  
  53.   
  54.     /** 获得View中心位置到边界的距离 */  
  55.     private static int getCenterOfView(View view) {  
  56.         return view.getLeft() + view.getWidth() / 2;  
  57.     }  
  58.       
  59.     @Override  
  60.     protected void onSizeChanged(int w, int h, int oldw, int oldh) {  
  61.         mCoveflowCenter = getCenterOfCoverflow();  
  62.         super.onSizeChanged(w, h, oldw, oldh);  
  63.     }  
  64.   
  65.     @Override  
  66.     protected boolean getChildStaticTransformation(View child, Transformation trans) {  
  67.         final int childCenter = getCenterOfView(child);  
  68.         final int childWidth = child.getWidth();  
  69.         int rotationAngle = 0;  
  70.   
  71.         trans.clear();  
  72.         trans.setTransformationType(Transformation.TYPE_BOTH);      // alpha和 matrix都变换  
  73.   
  74.         if (childCenter == mCoveflowCenter) {   //正中间的childView   
  75.             transformImageBitmap((ImageView) child, trans, 0);    
  76.         } else {                                //两侧的childView     
  77.             rotationAngle = (int) ( ( (float) (mCoveflowCenter - childCenter) / childWidth ) * mMaxRotationAngle );  
  78.             if (Math.abs(rotationAngle) > mMaxRotationAngle) {  
  79.                 rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle;  
  80.             }  
  81.             transformImageBitmap((ImageView) child, trans, rotationAngle);  
  82.         }  
  83.   
  84.         return true;  
  85.     }  
  86.   
  87.     private void transformImageBitmap(ImageView child, Transformation trans, int rotationAngle) {  
  88.         mCamera.save();  
  89.           
  90.         final Matrix imageMatrix = trans.getMatrix();  
  91.         final int imageHeight = child.getLayoutParams().height;  
  92.         final int imageWidth = child.getLayoutParams().width;  
  93.         final int rotation = Math.abs(rotationAngle);  
  94.   
  95.         //在Z轴上正向移动camera的视角,实际效果为放大图片; 如果在Y轴上移动,则图片上下移动; X轴上对应图片左右移动  
  96.         mCamera.translate(0.0f, 0.0f, 200.0f);  
  97.   
  98.         // As the angle of the view gets less, zoom in  
  99.         if (rotation < mMaxRotationAngle) {  
  100.             float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));  
  101.             mCamera.translate(0.0f, 0.0f, zoomAmount);  
  102.         }  
  103.   
  104.         mCamera.rotateY(rotationAngle);     //rotationAngle 为正,沿y轴向内旋转; 为负,沿y轴向外旋转  
  105.           
  106.         mCamera.getMatrix(imageMatrix);  
  107.         imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));  
  108.         imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));  
  109.           
  110.         mCamera.restore();  
  111.     }  
  112. }  

2.接下来就是要为图片添加倒影了,用过PhotoShop的都知道添加倒影就是将原有图片倒置,设置渐变式的显示,再将其放在原图片下面就行了,这里的方法也是一样

在为Gallery添加图片的同时,为每个图片添加倒影,需要在Adapter中做

下面就是相关代码 ImageAdapter.java:

[java]  view plain  copy
 print ?
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. import android.content.Context;  
  7. import android.graphics.Bitmap;  
  8. import android.graphics.Bitmap.Config;  
  9. import android.graphics.BitmapFactory;  
  10. import android.graphics.Canvas;  
  11. import android.graphics.LinearGradient;  
  12. import android.graphics.Matrix;  
  13. import android.graphics.Paint;  
  14. import android.graphics.PorterDuff.Mode;  
  15. import android.graphics.PorterDuffXfermode;  
  16. import android.graphics.Shader.TileMode;  
  17. import android.view.View;  
  18. import android.view.ViewGroup;  
  19. import android.widget.BaseAdapter;  
  20. import android.widget.ImageView;  
  21. import android.widget.ImageView.ScaleType;  
  22.   
  23. public class ImageAdapter extends BaseAdapter {  
  24.     private ImageView[] mImages; // 存储每个图片的ImageView  
  25.   
  26.     private Context mContext;  
  27.     public List<Map<String, Object>> list;  
  28.   
  29.     public Integer[] imgs = { R.drawable.img1, R.drawable.img2,  
  30.             R.drawable.img3, R.drawable.img4, R.drawable.img5 };  
  31.     public String[] titles = { "孙燕姿""就是要唱歌""微笑""大海""漂亮"};  
  32.   
  33.     public ImageAdapter(Context c) {  
  34.         this.mContext = c;  
  35.         list = new ArrayList<Map<String, Object>>();  
  36.         for (int i = 0; i < imgs.length; i++) {  
  37.             HashMap<String, Object> map = new HashMap<String, Object>();  
  38.             map.put("image", imgs[i]);  
  39.             list.add(map);  
  40.         }  
  41.         mImages = new ImageView[list.size()];  
  42.     }  
  43.   
  44.     /** 
  45.      * 创建倒影效果 
  46.      */  
  47.     @SuppressWarnings("deprecation")  
  48.     public boolean createReflectedImages() {  
  49.         final int reflectionGap = 4;//原图与倒影之间的间隙  
  50.         int index = 0;  
  51.         for (Map<String, Object> map : list) {  
  52.             Integer id = (Integer) map.get("image");  
  53.             Bitmap originalImage = BitmapFactory.decodeResource(  
  54.                     mContext.getResources(), id); // 获得图片资源  
  55.             // 获得图片的长宽  
  56.             int width = originalImage.getWidth();  
  57.             int height = originalImage.getHeight();  
  58.   
  59.             Matrix matrix = new Matrix();  
  60.             matrix.preScale(1, -1); // 实现图片的反转  
  61.             Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,  
  62.                     height / 2, width, height / 2, matrix, false); // 创建反转后的图片Bitmap对象,图片高是原图的一半  
  63.             Bitmap bitmapWithReflection = Bitmap.createBitmap(width,  
  64.                     (height + height / 2), Config.ARGB_8888); // 创建标准的Bitmap对象,宽和原图一致,高是原图的1.5倍  
  65.   
  66.             Canvas canvas = new Canvas(bitmapWithReflection);  
  67.             canvas.drawBitmap(originalImage, 00null); // 创建画布对象,将原图画于画布,起点是原点位置  
  68.             Paint paint = new Paint();  
  69.             canvas.drawRect(0, height, width, height + reflectionGap, paint);  
  70.             canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); // 将反转后的图片画到画布中  
  71.   
  72.             paint = new Paint();  
  73.             LinearGradient shader = new LinearGradient(0,  
  74.                     originalImage.getHeight(), 0,  
  75.                     bitmapWithReflection.getHeight() + reflectionGap,  
  76.                     0x70ffffff0x00ffffff, TileMode.MIRROR);// 创建线性渐变LinearGradient对象  
  77.             paint.setShader(shader); // 绘制  
  78.             paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));//倒影遮罩效果  
  79.             canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()  
  80.                     + reflectionGap, paint); // 画布画出反转图片大小区域,然后把渐变效果加到其中,就出现了图片的倒影效果  
  81.   
  82.             ImageView imageView = new ImageView(mContext);  
  83.             imageView.setImageBitmap(bitmapWithReflection); // 设置带倒影的Bitmap  
  84.             //设置ImageView的大小,可以根据图片大小设置  
  85.             // imageView.setLayoutParams(newmyGallery.LayoutParams(width,height));  
  86.             imageView.setLayoutParams(new myGallery.LayoutParams(250500));//设置ImageView的大小,可根据需要设置固定宽高  
  87.             imageView.setScaleType(ScaleType.FIT_CENTER);//将图片按比例缩放  
  88.             mImages[index++] = imageView;  
  89.         }  
  90.         return true;  
  91.     }  
  92.   
  93.     @Override  
  94.     public int getCount() {  
  95.         return imgs.length;  
  96.     }  
  97.   
  98.     @Override  
  99.     public Object getItem(int position) {  
  100.         return mImages[position];  
  101.     }  
  102.   
  103.     @Override  
  104.     public long getItemId(int position) {  
  105.         return position;  
  106.     }  
  107.   
  108.     @Override  
  109.     public View getView(int position, View convertView, ViewGroup parent) {  
  110.         return mImages[position]; // 获得Gallery中对应位置的ImageView  
  111.     }  
  112.   
  113.     public float getScale(boolean focused, int offset) {  
  114.         return Math.max(01.0f / (float) Math.pow(2, Math.abs(offset)));  
  115.     }  
  116.   
  117. }  


3.然后在主Activity中进行配置Main.java:

[java]  view plain  copy
 print ?
  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.view.View;  
  4. import android.widget.AdapterView;  
  5. import android.widget.AdapterView.OnItemClickListener;  
  6. import android.widget.AdapterView.OnItemSelectedListener;  
  7. import android.widget.TextView;  
  8. import android.widget.Toast;  
  9.   
  10. public class Main extends Activity {  
  11.   
  12.     private TextView tvTitle;     
  13.     private myGallery gallery;    
  14.     private ImageAdapter adapter;  
  15.       
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.   
  21.         initRes();  
  22.     }  
  23.       
  24.     private void initRes(){        
  25.         tvTitle = (TextView) findViewById(R.id.tvTitle);        
  26.         gallery = (myGallery) findViewById(R.id.mygallery);     // 获取自定义的myGallery控件        
  27.                  
  28.         adapter = new ImageAdapter(this);           
  29.         adapter.createReflectedImages();    // 创建倒影效果        
  30.         gallery.setAdapter(adapter);        
  31.                      
  32.         gallery.setOnItemSelectedListener(new OnItemSelectedListener() {    // 设置选择事件监听        
  33.             @Override   
  34.             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {        
  35.                 tvTitle.setText(adapter.titles[position]);        
  36.             }        
  37.                  
  38.             @Override   
  39.             public void onNothingSelected(AdapterView<?> parent) {        
  40.             }        
  41.         });        
  42.                  
  43.         gallery.setOnItemClickListener(new OnItemClickListener() {          // 设置点击事件监听        
  44.             @Override   
  45.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        
  46.                 Toast.makeText(Main.this"img " + (position+1) + " selected", Toast.LENGTH_SHORT).show();        
  47.             }        
  48.         });        
  49.     }  
  50. }  

4.最后是页面布局main.xml:

[html]  view plain  copy
 print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.     <TextView  
  7.         android:id="@+id/tvTitle"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerHorizontal="true"  
  11.         android:textSize="16sp" />  
  12.   
  13.     <com.homer.reflect.myGallery  
  14.         android:id="@+id/mygallery"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_alignParentLeft="true"  
  18.         android:layout_centerVertical="true" />  
  19.   
  20. </RelativeLayout>  


5.大功告成啦!看看效果:



 欢迎下载源码!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值