如何在Android中实现视差滚动

如何在Android中实现视差滚动

什么是视差滚动?

视差滚动原本是一个天文学术语,当我们观察星空的时候,离我们比较远的星星移动速度比较慢,离我们比较近的星星移动速度比较快,当我们坐在车上向车窗外看的时候也会有这种体验,远处的群山似乎没有移动,但近处的行道树却在飞速掠过。

在工程设计中,视差滚动是指通过为背景图像设定比前景图像更慢的移动速度模拟现实世界中人类的视觉体验,从而在 2D 场景中产生深度的错觉,增加沉浸感。

以下是几个设计实例:

img

NASA Prospect

img

Cyclemon

img

Bearideas

img

Fluttuo

如何在 Android 中实现视差滚动?

首先创建一个新项目

  • 新建 Android project
  • 选择 Empty Activity
  • Name:ParallaxAndroid
  • Package name:com.example.parallaxandroid
  • Language:Kotlin

然后添加需要的依赖:

implementation "androidx.coordinatorlayout:coordinatorlayout:1.1.0"
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.google.android.material:material:1.2.0-alpha06'

此处以创建一个具有视差滚动效果的展示书籍磁贴的页面为例。

首先从 XML 布局开始。

在 main activity XML 中添加 collapsing toolbar layout,collapsing toolbar layout 类似 FrameLayout,所有最后加入的元素都将被放置在顶部。这种放置方式对实现视差滚动非常重要。

<androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.appbar.AppBarLayout>
    <com.google.android.material.appbar.CollapsingToolbarLayout>
        <ImageView/>
        <android.appcompat.widget.Toolbar />
        <com.google.android.material.tabs.TabLayout/>
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager/>
</androidx.coordinatorlayout.widget.CoordinatorLayout> 

activity_main.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true">

        <include layout="@layout/toolbar"/>

        <com.google.android.material.tabs.TabLayout
            android:id
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值