如何使图像居中并具有正确的大小的解决方案是什么?
在使用React Native中的Flexbox的文档中,我们可以了解到为什么您的尝试失败了。
"justifyContent"描述了如何在容器的主轴上对齐"children"(在React Native中默认为纵向)。
"alignItems"描述了如何沿容器的交叉轴对齐"children"。
因此,在
<Image />
元素上设置
alignItems
和
justifyContent
会影响图像的
子元素的位置。
但在你的情况下,
<Image />
没有任何子元素,所以效果是零。
如何使你的代码按预期工作
要为图像设置样式,我们需要为图像的父元素设置alignItems
和justifyContent
,在你的情况下,父元素是<View />
元素。
假设<View />
的样式是container
(<Image />
的样式是logo
),以下样式设置将使图像在两个方向上居中。1
import React from 'react';
import { Image, StyleSheet, View } from 'react-native';
const logoImage = { uri: 'https://istack.dev59.com/15jTl.webp' };
export default function LoadingScreen() {
return (
<View style={styles.container}>
<Image style={styles.logo} source={logoImage} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logo: {
width: 280,
height: 260,
},
});
另一种解决方案
alignSelf
与alignItems
具有相同的选项和效果,但不是影响容器内的子元素,而是可以将此属性应用于单个元素。
只需在图像本身上设置alignSelf
,而不是在其父元素上设置alignItems
。
如果图像应该居中,而图像下方有应该左对齐的文本,则此方法非常方便。
请考虑下面的示例。
在纵向模式下,所有内容都适合屏幕,并且在水平和垂直方向上居中。
在横向模式下,图像+文本无法在垂直方向上适应。
当向顶部滚动时,应显示整个图像,而当向底部滚动时,应显示所有文本。2
import React from 'react';
import { Image, ScrollView, StyleSheet, Text, View } from 'react-native';
const logoImage = { uri: 'https://istack.dev59.com/15jTl.webp' };
export default function LoadingScreen() {
return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.scrollView}>
<Image style={styles.logo} source={logoImage} />
<Text>Here are some</Text>
<Text>lines of text</Text>
<Text>below the image.</Text>
<Text> - - -</Text>
<Text>I want the image</Text>
<Text>to be centered,</Text>
<Text>but this text</Text>
<Text>to be left-aligned,</Text>
<Text>not centered.</Text>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 8 },
scrollView: { flexGrow: 1, justifyContent: 'center' },
logo: { alignSelf: 'center', width: 280, height: 260 },
});
1
flex: 1
这个语句使得container
占据整个屏幕高度,而不仅仅是图片的高度。
2
要复现:下载并解压到您选择的某个目录中。
切换到该目录并运行npm install
,然后运行npm start
。
(您还需要一个模拟器或实体设备来运行应用程序。)
}, logo: { width: 220, height: 300, marginTop: -50, },
}); - wuno