Android 自定义Gallery浏览图片

时间:2014-04-28 16:06:46   收藏:0   阅读:714

之前写的《Android ImageSwitcher和Gallery的使用》一文中提到我在教室一下午为实现那个效果找各种资料。期间在网上找了一个个人觉得比较不错的效果,现在贴图上来:

bubuko.com,布布扣

其实这个效果使用的知识点就是图像的获取、创建、缩放、旋转、Matrix类、Canvas类等,另外就是自定义的Gallery控件。

相信大家都期待马上上代码了吧,嘻嘻。(注释比较多,相信大家都能看懂。)

main.xml:

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/background_light" >

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="16sp" />
    
    <com.example.demo.GalleryView        
        android:id="@+id/mygallery"
        android:spacing="20dp"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:unselectedAlpha="1.2"
        android:layout_below="@id/tvTitle"
        android:layout_marginTop="10dip" />

</RelativeLayout>
bubuko.com,布布扣

新建一个GalleryView类:

bubuko.com,布布扣
public class GalleryView extends Gallery {

    private Camera mCamera = new Camera();
    private int mMaxRotationAngle = 60; // 最大旋转角度 60
    private int mMaxZoom = -120;
    private int mCoveflowCenter;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // e1是按下的事件,e2是抬起的事件
        int keyCode;
        if (isScrollingLeft(e1, e2)) {
            keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(keyCode, null);
        return true;
        
    }

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
        return e2.getX() > e1.getX();
    }

    public GalleryView(Context context) {
        super(context);
        this.setStaticTransformationsEnabled(true);
    }

    public GalleryView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setStaticTransformationsEnabled(true);
    }

    public GalleryView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setStaticTransformationsEnabled(true);
    }

    public int getMaxRotationAngle() {
        return mMaxRotationAngle;
    }

    public void setMaxRotationAngle(int maxRotationAngle) {
        mMaxRotationAngle = maxRotationAngle;
    }

    public int getMaxZoom() {
        return mMaxZoom;
    }

    public void setMaxZoom(int maxZoom) {
        mMaxZoom = maxZoom;
    }

    /** 获取Gallery的中心x */
    private int getCenterOfCoverflow() {
        return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
                + getPaddingLeft();
    }

    /** 获取View的中心x */
    private static int getCenterOfView(View view) {
        return view.getLeft() + view.getWidth() / 2;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        mCoveflowCenter = getCenterOfCoverflow();
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected boolean getChildStaticTransformation(View child,
            Transformation trans) {
        final int childCenter = getCenterOfView(child);
        final int childWidth = child.getWidth();
        int rotationAngle = 0;

        trans.clear();
        trans.setTransformationType(Transformation.TYPE_BOTH); // alpha 和 matrix
                                                                // 都变换

        if (childCenter == mCoveflowCenter) { // 正中间的childView
            transformImageBitmap((ImageView) child, trans, 0);
        } else { // 两侧的childView
            rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
            if (Math.abs(rotationAngle) > mMaxRotationAngle) {
                rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
                        : mMaxRotationAngle;
            }
            transformImageBitmap((ImageView) child, trans, rotationAngle);
        }

        return true;
    }

    private void transformImageBitmap(ImageView child, Transformation trans,
            int rotationAngle) {
        mCamera.save();

        final Matrix imageMatrix = trans.getMatrix();
        final int imageHeight = child.getLayoutParams().height;
        final int imageWidth = child.getLayoutParams().width;
        final int rotation = Math.abs(rotationAngle);

        // 在Z轴上正向移动camera的视角,实际效果为放大图片; 如果在Y轴上移动,则图片上下移动; X轴上对应图片左右移动。
        mCamera.translate(0.0f, 0.0f, -20.0f);

        // As the angle of the view gets less, zoom in
        if (rotation < mMaxRotationAngle) {
            float zoomAmount = (float) (mMaxZoom + (rotation * 1.0));
            mCamera.translate(0.0f, 0.0f, zoomAmount);
        }

        mCamera.rotateY(rotationAngle); // rotationAngle 为正,沿y轴向内旋转; 为负,沿y轴向外旋转

        mCamera.getMatrix(imageMatrix);
        imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
        imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

        mCamera.restore();
    }
}
View Code

再新建一个适配器类:ImageAdapter.java(最重要的地方)

bubuko.com,布布扣
public class ImageAdapter extends BaseAdapter {
    private ImageView[] mImages; // 保存倒影图片的数组

    private Context mContext;
    public List<Map<String, Object>> list;

    public Integer[] imgs = { R.drawable.image01, R.drawable.image02,
            R.drawable.image03, R.drawable.image04, R.drawable.image05,
            R.drawable.image06, R.drawable.image07 };
    public String[] titles = { "美图01", "美图02", "美图03", "美图04", "美图05", "美图06",
            "美图07" };

    public ImageAdapter(Context c) {
        this.mContext = c;
        list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < imgs.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("image", imgs[i]);
            list.add(map);
        }
        mImages = new ImageView[list.size()];
    }

    /** 反射倒影 */
    public boolean createReflectedImages() {
        final int reflectionGap = 4;
        final int Height = 300;
        int index = 0;
        for (Map<String, Object> map : list) {
            Integer id = (Integer) map.get("image");
            // 根据给定的资源ID从指定的资源中解析、创建Bitmap对象。
            Bitmap originalImage = BitmapFactory.decodeResource(
                    mContext.getResources(), id); // 获取原始图片
            // 获得实际图片的宽高
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();
            float scale = Height / (float) height;

            Matrix sMatrix = new Matrix();
            // 第一次缩放图片动作
            sMatrix.postScale(scale, scale);

            Bitmap miniBitmap = Bitmap.createBitmap(originalImage, 0, 0,
                    originalImage.getWidth(), originalImage.getHeight(),
                    sMatrix, false);
            // 获取第一次缩放后的图片的宽高
            int mwidth = miniBitmap.getWidth();
            int mheight = miniBitmap.getHeight();
            Matrix matrix = new Matrix();
            matrix.preScale(1, -1); // 图片矩阵变换(从低部向顶部的倒影)
            Bitmap reflectionImage = Bitmap.createBitmap(miniBitmap, 0,  mheight/2,
                    mwidth, mheight/2, matrix, false); // 截取原图下半部分
            Bitmap bitmapWithReflection = Bitmap.createBitmap(mwidth,
                    mheight+mheight/2, Config.ARGB_8888);// 创建倒影图片(高度为原图3/2)

            Canvas canvas = new Canvas(bitmapWithReflection); // 绘制倒影图(原图 + 间距 +
                                                                // 倒影)
            canvas.drawBitmap(miniBitmap, 0, 0, null); // 绘制原图
            Paint paint = new Paint();
            canvas.drawRect(0, mheight, mwidth, mheight , paint); // 绘制原图与倒影的间距
            canvas.drawBitmap(reflectionImage, 0, mheight , null); // 绘制倒影图,绘制原图与倒影的间距(第四个参数改变)

            paint = new Paint();
            LinearGradient shader = new LinearGradient(0,
                    miniBitmap.getHeight(), 0, bitmapWithReflection.getHeight()
                            + reflectionGap, 0x70ffffff, 0x00ffffff,
                    TileMode.CLAMP);
            paint.setShader(shader); // 线性渐变效果
            paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // 倒影遮罩效果
            canvas.drawRect(0, mheight, mwidth,
                    bitmapWithReflection.getHeight() + reflectionGap, paint); // 绘制倒影的阴影效果

            ImageView imageView = new ImageView(mContext);
            imageView.setImageBitmap(bitmapWithReflection); // 设置倒影图片
            imageView.setLayoutParams(new GalleryView.LayoutParams(
                    (int) (width * scale),
                    (int) (mheight * 3 / 2.0+ reflectionGap)));
            imageView.setScaleType(ScaleType.MATRIX);
            mImages[index++] = imageView;
        }
        return true;
    }

    @Override
    public int getCount() {
        return imgs.length;
    }

    @Override
    public Object getItem(int position) {
        return mImages[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return mImages[position]; // 显示倒影图片(当前获取焦点)
    }

    public float getScale(boolean focused, int offset) {
        return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
    }

}
View Code

最后就是Main.java(默认Activity):

bubuko.com,布布扣
public class Main extends Activity {

    private TextView tvTitle;     
    private GalleryView gallery;     
    private ImageAdapter adapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initRes();
    }
    
    private void initRes(){
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        gallery = (GalleryView) findViewById(R.id.mygallery);

        adapter = new ImageAdapter(this);     
        adapter.createReflectedImages();    // 创建倒影效果
        gallery.setAdapter(adapter);
        
        gallery.setOnItemSelectedListener(new OnItemSelectedListener() {    // 设置选择事件监听
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tvTitle.setText(adapter.titles[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        gallery.setOnItemClickListener(new OnItemClickListener() {            // 设置点击事件监听
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(Main.this, "img " + (position+1) + " selected", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
View Code

接下来运行即可。你就能看到上面的运行效果了。

Android 自定义Gallery浏览图片,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!