项目中需要实现画廊效果的布局,网上的demo一大推,基本上是大同小异。也能够实现我需求,我将网上的源码移植运行后,发现并不是他们文章的描述的那样的效果。如下图:
Gallery的效果是参考这个链接 http://android.tgbus.com/Android/tutorial/201108/362438.shtml
从上图中可以看到Gallery中间显示的图片是不正常的,理论上正中间的图片应该是没有旋转角度的。从源码可以看到,在getChildStaticTransformation()这个方法中的,判断Gallery的item是否是在屏幕中间这部分出了问题。方法如下:
protected boolean getChildStaticTransformation(View child, Transformation t) { //取得当前子view的半径值 final int childCenter = getCenterOfView(child); System.out.println("childCenter:"+childCenter); final int childWidth = child.getWidth(); //旋转角度 int rotationAngle = 0; //重置转换状态 t.clear(); //设置转换类型 t.setTransformationType(Transformation.TYPE_MATRIX); //如果图片位于中心位置不需要进行旋转 if (childCenter == mCoveflowCenter) { transformImageBitmap((ImageView) child, t, 0); } else { //根据图片在gallery中的位置来计算图片的旋转角度 rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle); System.out.println("rotationAngle:" +rotationAngle); //如果旋转角度绝对值大于最大旋转角度返回(-mMaxRotationAngle或mMaxRotationAngle;) if (Math.abs(rotationAngle) > mMaxRotationAngle) { rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle; } transformImageBitmap((ImageView) child, t, rotationAngle); } return true; }
当childCenter == mCoverflowCenter 时,说明这个item在正中间,此时传给transformImageBitmap()方法的第三个参数,即旋转角度是0。代表是不旋转的。而出现上述bug,说明childCenter!=mCoveflowCenter 。经过一天的debug,和百度,google,终于是知道了上述问题的原因。
从Android3.0(API Level 11)开始,Android 2D渲染管道能够更好的支持硬件加速。硬件加速执行的所有的绘图操作都是使用GPU在View对象的画布上来进行的。因为启用硬件加速会增加资源的需求,因此这样的应用会占用更多的内存。从API 14开始,android默认是打开硬件加速的,其自带的所有的View都是支持硬件加速的,但是我们自定义的控件则有时候会出现问题。在此demo中我们自定义的Gallery就不支持硬件加速。解决办法就是在这个Activity的配置中加上
android:hardwareAccelerated="false"