【发布时间】:2017-08-31 02:54:44
【问题描述】:
我正在尝试在 react native 中创建一个 UI,该 UI 包含一个带有外部阴影的框。使用我已经完成的图像,但是有什么合适的方法吗?
【问题讨论】:
我正在尝试在 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。
【讨论】:
iOS 和overflow: 'hidden'; 消失所有阴影,所以如果你想看到所有的阴影省略overflow: 'hidden';。
我找到了一种解决方法,使用线性渐变来解决非常相似的问题。我在堆栈上的任何地方都没有找到更好的东西,所以我想我会在这里添加它。如果您只想要顶部和底部或侧面阴影,它会特别好和容易。
我为全宽和 140 高的图像添加了顶部和底部的内框阴影。您可以创建多个渐变来制作外框阴影。不要忘记角落。你可以使用 start 和 end 道具来制作有角度的阴影/渐变,如果你需要的话,也许这对角落有用。
<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。
【讨论】:
您可以使用库“react-native-shadow-2”,适用于 android 和 iOS。 无需为 iOS/android 编写单独的代码块,并且还支持打字稿。
安装:
结构:
import { Shadow } from 'react-native-shadow-2';
<Shadow>
{/* Your component */}
</Shadow>
有startColor、finalColor、radius、offset等很多props。您可以根据自己的要求使用。
【讨论】: