介绍
不透明度是指用于控制元素可见性的对象或元素的透明度。它有助于逐步进入和逐步退出,以防止任何可能对用户产生负面影响的不和谐的布局移动。当不透明度值发生更改时,它会影响执行此类更改的组件的可见性。
您可以设置从 0 到 1 的不透明度值,这相当于 0% 到 100%。因此,例如,我们可以根据我们想要多少可见性或透明度或当时传达给用户的信息,将我们的不透明度值设置为 0.1 或 0.5。
动画不透明度的好处
先决条件
入门
让我们使用以下命令创建一个新的 expo 项目:
npx create-expo-app rn-opacity
在我们刚刚创建的应用程序的根目录中,有一个 App.js 文件,其中包含一个启动代码,以显示应用程序在安装后已启动并正常运行。
因此,让我们分别使用命令 yarn ios for iOS 和 yarn android for android 运行我们的应用程序,我们将看到组件的内容出现在我们的屏幕上。
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';export default function App() {
return (
Open up App.js to start working on your app!
);
}const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
构建用户界面
我们可以添加一个组件结构来演示我们的示例吗? 是的,这是可能的!
在我们的源代码中是一个橙色框,我们使用 View 组件来构建 UI 并将 backgroundColor 设置为橙色
我们在第 1 行导入 react 库。
在第 2 行,我们导入 StyleSheet 用于编写外部样式,View 用于构建我们的 UI,以及 TouchableWithoutFeedback 按钮组件用于实现交互或状态切换触发。
import React from "react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, View, TouchableWithoutFeedback } from "react-native";export default function App() {
return (
null}>
);
}const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
box: {
backgroundColor: "orange",
height: 200,
width: 200,
opacity: 0.5,
}
});
把所有东西放在一起
在下面的 App.js 文件中,我们添加了相当多的更改,让我们通过代码行进行解释。
import React, { useRef } from "react";
import { StatusBar } from "expo-status-bar";
import {
StyleSheet,
View,
TouchableWithoutFeedback,
Animated,
} from "react-native";export default function App() { const opacityAnimation = useRef(new Animated.Value(0.5)).current;
const opacityStyle = { opacity: opacityAnimation }; const animateElement = () => { Animated.timing(opacityAnimation, {
toValue: 0,
duration: 1500,
useNativeDriver: true
}).start(() => {
Animated.timing(opacityAnimation, {
toValue: 1,
duration: 1500,
useNativeDriver: true
}).start()
})
}; return (
animateElement()}>
);
}const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
box: {
backgroundColor: "orange",
height: 200,
width: 200,
opacity: 0.5,
},
});
我们声明一个 opacityAnimation 变量来保存设置为 0.5 的 Animated.value。这意味着我们的盒子在渲染时默认的不透明度值为 0.5
在第 13 行,在我们的代码中,我们还声明了一个变量来保存我们将动态更改的 opacity 样式的对象,并将 opacity 属性设置为 opacityAnimation 的值。
在 animateElement 函数中,我们访问 Animated.timing 方法。 Timing 会将单个值的动画在设定的时间段内指定为另一个值,因此它的函数签名是 opacityAnimation 然后是配置对象。在我们的配置对象中,我们有以下选项:
要触发更改,我们需要调用源代码中的 start 方法。
此外,在我们渲染 UI 的地方,我们用 Animated.View 组件替换了 View 组件。 Animated 库包裹着普通的 View 元素
在我们的 TouchableWithoutFeedback 按钮组件中调用 animateElement 函数。它在哪里被传递到 onPress 函数道具中。
在框区域内单击将触发我们的动画,使其在两次调用中从 0.5 淡出到 0,然后从 0 淡入到 1 持续 1500 毫秒。
这是该应用程序的演示:
概括
可以应用此功能的一个很好的用例是在 Button 组件、Checkbox 组件和 Radio Button 组件中。 您会发现此实现对于在与您的应用程序交互时实现吸引用户的视觉效果很有用。
感谢您的光临,希望您发现本教程对您有用。
关注七爪网,获取更多APP/小程序/网站源码资源!
留言与评论(共有 0 条评论) “” |