我正在尝试在 React Native 中创建一个 UI,该 UI 包含一个带有外部阴影的框。使用图像我已经做到了,但是有什么正确的方法可以做到这一点吗?
您必须为 iOS 和 Android 使用不同样式的道具。
安卓
对于 Android 来说非常简单,只需使用
elevation
样式属性(参见 docs)。一个例子:
boxWithShadow: {
elevation: 5
}
iOS
在 iOS 中,您有更大的灵活性,请使用 Shadow 道具(请参阅docs)。一个例子:
boxWithShadow: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.8,
shadowRadius: 1,
}
总结
总而言之,要获得两个平台的盒子阴影,请使用两组样式道具:
boxWithShadow: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 5
}
注意: 不要使用
overflow: 'hidden';
,在iOS
中所有阴影都会因该属性而消失。
嘿,看现在完成了!
const styles = StyleSheet.create({
shadow: {
borderColor:'yourchoice', // if you need
borderWidth:1,
overflow: 'hidden',
shadowColor: 'yourchoice',
shadowRadius: 10,
shadowOpacity: 1,
}
});
请记住,影子的道具仅适用于 IOS。
您可以使用库“react-native-shadow-2”,适用于 Android 和 iOS。 无需为 iOS/android 编写单独的代码块,并且还支持打字稿。
安装:
结构:
import { Shadow } from 'react-native-shadow-2';
<Shadow>
{/* Your component */}
</Shadow>
有很多属性,例如startColor、finalColor、radius、offset。您可以根据您的要求使用。
有时,即使组件上应用了阴影效果,但如果该组件占据了屏幕的整个宽度和高度,则可能不会立即可见。在这种情况下,建议通过添加边距、更改背景颜色或使用其他视觉提示在组件与其周围环境之间创建对比度来调整组件的样式。这可以帮助突出阴影效果并使其更容易被用户注意到。
风格
import { Platform } from 'react-native';
const styles = StyleSheet.create({
box: {
...Platform.select({
ios: {
shadowColor: 'rgba(0, 0, 0, 1)',
shadowOpacity: 0.5,
shadowRadius: 5,
shadowOffset: {
height: 5,
width: 5,
},
},
android: {
elevation: 5,
backgroundColor: 'rgba(0, 0, 0, 1)',
},
}),
},
});
组件
const Shadow = ({ children }) => {
return (
<View style={styles.box}>{children}</View>
);
};
我找到了一种使用线性渐变来解决非常类似问题的解决方法。我在堆栈上没有找到更好的东西,所以我想我会在这里添加它。如果您只想要顶部和底部或侧面阴影,这特别好且容易。
我向全宽、140 高度的图像添加了顶部和底部内框阴影。您可以创建多个渐变来制作外部框阴影。不要忘记角落。您可以使用开始和结束道具来制作有角度的阴影/渐变,如果您需要的话,也许这适用于角落。
<ImageBackground
source={imagePicker(this.props.title)}
style={styles.image}
>
<LinearGradient
colors={[
'transparent',
'transparent',
'rgba(0,0,0,0.2)',
'rgba(0,0,0,0.6)'
]}
start={[0,0.9]}
end={[0,1]}
style={styles.image_shadows}
/>
<LinearGradient
colors={[
'rgba(0,0,0,0.6)',
'rgba(0,0,0,0.2)',
'transparent',
'transparent'
]}
start={[0,0]}
end={[0,0.1]}
style={styles.image_cover}
/>
</ImageBackground>
const styles = StyleSheet.create({
image: {
flex: 1,
resizeMode: "stretch",
justifyContent: "center",
paddingTop:90,
paddingLeft:10,
height:140,
flexDirection: 'row',
},
image_shadows: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
height: 140
}
}
如果您使用 expo,您可以使用“expo install expo-linear-gradient”Expo Docs 安装它。如果没有,我相信 React-Native-Linear-Gradient 类似 React-Native-Linear-Gradient github。
它没有给初学者提供明确的答案