12.创建视图变换

12.1 问题

应用程序需要动态变换视图的外观,从而为视图添加一些视觉效果,例如视觉变换效果。

12.2 解决方案

(API Level 1)
Viewgroup中的静态变换API提供了应用视觉效果的简单方法,例如旋转、缩放、透明度变化,而且不必依靠动画。使用它也很容易使用父视图的上下文来应用变换,例如根据位置的变化而缩放。
在初始化过程中调用setStaticTranformationsEnabled(true),可以启用任何ViewGroup的静态变换。启动此功能后,框架会定期调用每个视图的getChildStaticTransformation(),从而允许应用程序设置变换。

12.3 实现机制

首先看一个示例,在该例中变换被应用一次而且不会改变(参见以下代码)。
使用静态变换自定义布局

public class PerspectiveLayout extends LinearLayout {

    public PerspectiveLayout(Context context) {
        super(context);
        init();
    }

    public PerspectiveLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PerspectiveLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    private void init() {
        // 启动静态变换,这样对每个视图都会调用getChildStaticTransformation()
        setStaticTransformationsEnabled(true);
    }

    @Override
    protected boolean getChildStaticTransformation(View child, Transformation t) {
        // 清除所有现有的变换
        t.clear();

        if (getOrientation() == HORIZONTAL) {
            // 根据到左边缘的距离对子视图进行缩放
            float delta = 1.0f - ((float) child.getLeft() / getWidth());

            t.getMatrix().setScale(delta, delta, child.getWidth() / 2,
                    child.getHeight() / 2);
        } else {
            // 根据顶端边缘的距离对子视图进行缩放
            float delta = 1.0f - ((float) child.getTop() / getHeight());

            t.getMatrix().setScale(delta, delta, child.getWidth() / 2,
                    child.getHeight() / 2);
            //同样也根据它的位置应用颜色淡出效果
            t.setAlpha(delta);
        }
        return true;
    }
}

这个示例介绍了一个自定义的LinearLayout,它根据子视图到父视图起始边缘的距离,对每个视图做了缩放变换。getChildStaticTransformation()中的代码通过子视图到父视图左边缘或顶端边缘的距离与父视图完整尺寸的比值计算得出应该使用的缩放比例。设定变换之后,这个方法的返回值会通知Android框架。任何情况下,只有应用程序中设置了一个自定义变换,这个方法就必须返回true,以确保它被关联到视图上。
大多数的视觉效果(如旋转或缩放)都实际地应用于Transformation的Matrix上。在我们的示例中,通过调用getMatrix().setScale()来调整每个子视图的缩放,同时传入缩放比例和轴心点。轴心点就是缩放发生的位置,我们将这个位置设置在视图的中心点,这样缩放的结果就会居中显示。
如果布局是垂直方向的,我们同样会根据相同的距离值为子视图应用透明渐变效果,只需要直接使用Transformation的setAlpha()方法即可。以下代码就是使用这个视图的示例布局:
res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- 水平方向自定义布局-->
    <com.examples.statictransforms.PerspectiveLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
    </com.examples.statictransforms.PerspectiveLayout>
    <!-- 垂直方向自定义布局-->
    <com.examples.statictransforms.PerspectiveLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
    </com.examples.statictransforms.PerspectiveLayout>
</LinearLayout>

下图显示了示例变换的结果。
水平视角和垂直视角布局
在水平布局中,越往右的视图使用的缩放比例越小。同样,垂直方向的缩放比例也是越往下越小。另外,垂直方向的视图由于添加了透明度变化会出现逐渐淡出的效果。
现在让我们看一下提供了更为动态变化效果的示例。以下代码展示了一个封装在HorizontalScrollView中的自定义布局。当子视图滚动时,这个布局使用静态变换来缩放子视图。在屏幕中心的视图大小总是正常的,越靠近边缘视图就越小。这样就会出现下面的效果:在滚动的过程中,视图首先会逐渐靠近,然后逐渐远离。
自定义视角滚动内容

public class PerspectiveScrollContentView extends LinearLayout {

    /* 每个子视图的缩放比例都是可调节的 */
    private static final float SCALE_FACTOR = 0.7f;
    /* 
     * 变换的轴心点。 (0,0)是左上, (1,1)是右下。当前设置的是底部中间(0.5,1)
     */
    private static final float ANCHOR_X = 0.5f;
    private static final float ANCHOR_Y = 1.0f;

    public PerspectiveScrollContentView(Context context) {
        super(context);
        init();
    }

    public PerspectiveScrollContentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public PerspectiveScrollContentView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        // 启动静态变换,这样对于每个子视图,getChildStaticTransformation()
        // 都会被调用
        setStaticTransformationsEnabled(true);
    }

    /*
     * 工具方法,用于计算屏幕坐标系内所有视图的当前位置
     */
    private int getViewCenter(View view) {
        int[] childCoords = new int[2];
        view.getLocationOnScreen(childCoords);
        int childCenter = childCoords[0] + (view.getWidth() / 2);

        return childCenter;
    }

    @Override
    protected boolean getChildStaticTransformation(View child, Transformation t) {
        HorizontalScrollView scrollView = null;
        if (getParent() instanceof HorizontalScrollView) {
            scrollView = (HorizontalScrollView) getParent();
        }
        if (scrollView == null) {
            return false;
        }

        int childCenter = getViewCenter(child);
        int viewCenter = getViewCenter(scrollView);
        // 计算子视图和父容器中心之间的距离,这会决定应用的缩放比例
        float delta = Math.min(1.0f, Math.abs(childCenter - viewCenter)
                / (float) viewCenter);
        //设置最小缩放比例为0.4
        float scale = Math.max(0.4f, 1.0f - (SCALE_FACTOR * delta));
        float xTrans = child.getWidth() * ANCHOR_X;
        float yTrans = child.getHeight() * ANCHOR_Y;
        
        //清除现有的所有变换
        t.clear();
        //为了视图设置变换
        t.getMatrix().setScale(scale, scale, xTrans, yTrans);

        return true;
    }
}

在这个示例中,自定义布局会根据每个子视图相对于父视图HorizontalScrollView中心位置的距离,为每个子视图计算变换。当用户滚动时,每个子视图的变换需要重新计算,从而实现视图移动时子视图的动态放大和缩小。这个示例将变换轴心点设置在每个子视图的底部中心位置,这会创作出如下效果:每个子视图会垂直放大,而且保持水平居中。以下代码的Activity示例将这个自定义布局付诸实践。
使用了PerspectiveScrollContentView的Activity

public class ScrollActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        HorizontalScrollView parentView = new HorizontalScrollView(this);
        PerspectiveScrollContentView contentView = new PerspectiveScrollContentView(this);
        
        // 对此视图禁用硬件加速,因为动态调整每个子视图的变换当前无法通过硬件实现
        // 也可以通过在清单文件中添加 android:hardwareAccelerated="false"
        // 禁用整个Activity或应用程序的硬件加速。但出于性能的考虑,最好尽可能少地
        // 禁用硬件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            contentView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        
        //向滚动条中添加几张图片
        for (int i = 0; i < 20; i++) {
            ImageView iv = new ImageView(this);
            iv.setImageResource(R.drawable.ic_launcher);
            contentView.addView(iv);
        }
        //添加要显示的布局
        parentView.addView(contentView);
        setContentView(parentView);
    }
}

在这个示例中创建一个滚动视图,并且关联了一个自定义的包含若干张滚动图片的PerspectiveScrollContentView。这里的代码不需要太多关注,但有个非常重要的地方需要提一下。虽然一般情况下静态变换都会被支持,但视图刷新过程中动态更新变换效果在当前SDK版本中是不能使用硬件加速的。因此,如果应用程序的目标SDK为11或以上版本,或者已经在某种程度上启用了硬件加速,这时需要对这个视图禁用硬件加速。
可以在清单文件的或整个标签中添加android:hardwareAccelerated="false"属性,对硬件加速进行全局设置;但是我们也可以通过调用setLayerType()方法并设置LAYER_TYPE_SOFTWARE,在Java代码中对这个自定义视图进行单独设置。如果应用程序的目标SDK版本低于此版本,即使是较新的设备,默认情况下硬件加速也是关闭的,处于兼容性考虑,这些代码也许是不必要的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值