【问题标题】:React Native: How to implement something like height: auto so that the image covers the view in width but doesn't stretchReact Native:如何实现类似 height: auto 以便图像在宽度上覆盖视图但不拉伸
【发布时间】:2021-11-08 07:50:13
【问题描述】:

我正在尝试在 react native 中将图像添加到视图中,并且我希望图像覆盖视图的整个宽度,因此我在样式中添加了 width: '100%',但我需要以整数形式输入高度要显示的图像。这就是我的代码的样子:

const SplashScreen = () => {
    return (
        <View style={styles.container}>
            <Text>Splash Screen</Text>
            <Image
                source={require('../assets/Login.png')}
                style={styles.logo}
            />
        </View>
    )
}

export default SplashScreen

const styles = StyleSheet.create({
    logo: {
        flex: 1,
        width: '100%',
        height: 300,
        resizeMode: 'contain',  
    }
}

我想使用 height:auto 之类的东西,而不是硬编码 height:300

这就是 vie 的样子:

谢谢大家

编辑:对于其他想知道的人,我只是在styles.container 中添加了一个height:'100%',然后我只需使用flex 调整图像的高度

示例:

logo: {
        flex: 0.5,
        width: '100%',
        resizeMode: 'contain', 
        backgroundColor: 'red' 
    }

【问题讨论】:

    标签: android react-native expo


    【解决方案1】:

    只需跳过为您的容器和图像提供“高度”的步骤。 您将拥有动态所需的高度

        logo: {
            flex: 1,
            width: '100%',
            aspectRatio:1 //If you know your aspect ratio use this or else divide your image width and height to get it..
            //height: 300, Commenting or removing this will make dynamically resize
            resizeMode: 'contain',
        }
    

    如果您不知道您的图像纵横比style={{ aspectRatio: image.width / image.height },请在您的图像标签中添加此属性@

    【讨论】:

    • 移除高度会完全从屏幕上移除图像
    • 使用纵横比
    猜你喜欢
    • 2018-01-26
    • 2021-12-13
    • 2012-03-27
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多