【问题标题】:How to put ImageBackground with resizeMode set to "contain" at the top?如何将 ResizeMode 设置为“包含”的 ImageBackground 放在顶部?
【发布时间】:2019-03-08 10:57:43
【问题描述】:

我目前正在使用以下代码在我的 React Native 应用程序上显示背景图像:

<ImageBackground 
   source={myImage} 
   style={{ width:'100%', height:'100%' }} 
   imageStyle={{resizeMode: 'contain'}}
>
....
</ImageBackground>

我不希望我的图像拉伸,resizeMode: 'contain' 完美地完成了这项工作。通过这种方式,图像不会覆盖我的所有屏幕,而只会覆盖其中的一部分,这正是我想要实现的。

我的问题是图像在中心与我上面显示的代码垂直对齐,而我希望它贴在顶部。所以它应该保持比例并保持在顶部。我尝试在 imageStyle 属性中使用 position:'absolute'top:0,但它不起作用。

我看到this question 显然解释了我的相同问题,但它没有为我的问题提供解决方案。

你有什么建议吗?

【问题讨论】:

  • 你使用resizeMode作为ImageBackground道具吗?
  • @HardikVirani 我刚试过。图像的大小也调整得很好,所以我认为使用 resizeMode 作为道具或样式属性的结果没有区别。无论哪种方式,定位仍然存在问题,因为图像已正确调整大小但显示在中心,所以我想将其垂直移动到顶部并粘贴在那里。

标签: css react-native background-image


【解决方案1】:

试试这个:

import {Dimensions} from 'react-native'

    constructor(props) {
      super(props);
      this.state = { height: 0 };
    }

    componentDidMount(){
          Image.getSize(imgUrl, (srcWidth, srcHeight) => {
             const maxHeight = Dimensions.get('window').height; 
             const maxWidth = Dimensions.get('window').width;
             const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
             this.setState({ height: srcHeight * ratio})
          })
    } 

    <ImageBackground 
       source={myImage} 
       style={{ flex:1 }} 
       resizeMode= 'contain'
       imageStyle={height: this.state.height, width:Dimensions.get('window').width}
    >
    ....
    </ImageBackground>

ImageBackgroundImage 相同的道具所以resizeMode 是道具而不是样式
看到这个:https://facebook.github.io/react-native/docs/imagebackground

【讨论】:

  • 好吧,resizeMode 也适用于您的方式,但图像仍垂直对齐在屏幕中心,而我希望它位于屏幕顶部。用resizeMode 显示图片的方式很好,问题是它的定位。
  • 查看编辑,添加您希望图像填充的height
  • 感谢您的编辑。这确实可行,保持比例并且图像位于顶部,但您的解决方案不是独立于设备的。在某些设备上,图像会贴在顶部,但不会贴在左右两侧。
  • 您希望图像填充宽度和高度为“自动”是吗?
  • 查看编辑,考虑到所有手机,我计算出全宽的最佳高度
【解决方案2】:

我使用静态高度和resizeMode覆盖实现了类似的效果

<ImageBackground 
  style={{ flex: 1 }}
  imageStyle={{ height: 300 }}
  source={{ uri: entity.picture }}
  resizeMode="cover"
>
  ...
</ImageBackground>

【讨论】:

    【解决方案3】:

    嘿,我真的不明白你需要做什么,试试这个

    body{
      margin: 0;
      padding: 0;
      font-family: sans-serif;
      background: url(background.jpg) no-repeat;
      /* background-size: cover; */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2013-05-19
      相关资源
      最近更新 更多