iOS平台React Native视图平面外旋转后被背景图裁切问题求助
React Native iOS 3D旋转视图被背景遮挡裁切问题解决
问题说明
在React Native中,对视图使用rotateX/rotateY做平面外旋转时,iOS平台下该视图会被父级ImageBackground遮挡并裁切,Android平台无此问题,设置zIndex无法解决。
原因
这不是React Native的bug,是iOS Core Animation的渲染机制导致:父视图的图层默认处于2D渲染上下文,子视图的3D变换会被父视图的平面边界裁切,且2D的zIndex不影响3D空间的层级关系。
解决方法
方法1:给父容器开启3D渲染上下文
给ImageBackground添加perspective和translateZ变换,让父图层进入3D空间,子视图的旋转就不会被裁切:
修改后的样式代码:
const styles = StyleSheet.create({ container: { flex: 1, }, image: { flex: 1, justifyContent: 'center', // 添加以下两行开启3D上下文 perspective: 300, transform: [{translateZ: 0}], }, text: { color: 'black', fontSize: 100, textAlign: 'center', transform: [ { perspective: 300 }, { rotateX: '30deg'}, ], }, });
方法2:将背景与旋转视图设为同级
把ImageBackground和需要旋转的视图放在同一层级,用绝对定位让背景铺满容器,这样旋转视图不在背景的子层级中,就不会被裁切:
修改后的组件代码:
const App = () => ( <View style={styles.container}> <ImageBackground source={image} resizeMode="cover" style={styles.image} /> <Text style={styles.text}>LOL</Text> </View> ); const styles = StyleSheet.create({ container: { flex: 1, }, image: { // 绝对定位铺满容器 position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, }, text: { color: 'black', fontSize: 100, textAlign: 'center', transform: [ { perspective: 300 }, { rotateX: '30deg'}, ], }, });
内容的提问来源于stack exchange,提问作者Nic
相关产品推荐
相关产品推荐

