【问题标题】:React Native Image absolute positioningReact Native Image 绝对定位
【发布时间】:2018-02-04 02:05:12
【问题描述】:

我正在尝试在底部边框放置两个图像,每边的宽度为 50%,以便正确缩放到任何设备尺寸。但我似乎无法获得任何绝对定位来以可重现的方式表现。

我做了一个示例小吃:https://snack.expo.io/rJd3OkVIM

App 组件及相关样式如下所示:

import React, { Component } from 'react';
import { View, StyleSheet, Image } from 'react-native';


export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Image
                style={styles.img}
                resizeMode="contain"
                resizeMethod="resize"
                source={require('./leftbg.png')}
            />
        <Image
                style={styles.imgr}
                resizeMode="contain"
                resizeMethod="resize"
                source={require('./rightbg.png')}
            />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
  },
    img: {
      width: '50%',
      position: 'absolute',
      left: 0,
    },
    imgr: {
      width: '50%',
      position: 'absolute',
      right: 0,
    }
});

每个设备将图像垂直居中设置为屏幕的随机部分,每次打开项目时居中似乎都会改变。

【问题讨论】:

  • 将高度设置为“100%”会有帮助吗?
  • 不,这实际上会使图像垂直居中。

标签: react-native react-native-image


【解决方案1】:

为了满足您的要求,让 ViewflexDirection: 'row' 包装 2 个图像,然后将顶级 ViewjustityContent: 'flex-end'

我做了一个简单的代码,硬代码高度为200 px,并将背景设置为goldenrod,以便于识别。

如果您需要保持图像的比例,请按照以下答案操作:Maintain aspect ratio of image with full width in React Native

import React, { Component } from 'react';
import { View, StyleSheet, Image } from 'react-native';


export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={{ flexDirection: 'row', height: 200, backgroundColor: 'goldenrod' }}>
          <Image
                style={styles.img}
                source={require('./leftbg.png')}
            />
          <Image
                  style={styles.imgr}
                  source={require('./rightbg.png')}
              />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
    justifyContent: 'flex-end',
  },
    img: {
      width: '50%',
      height: '100%',
      resizeMode: 'cover',
    },
    imgr: {
      width: '50%',
      height: '100%',
      resizeMode: 'cover',
    }
});

【讨论】:

  • 但这使用高度作为约束,而不是宽度。
  • 不确定我是否理解,但这是我的想法:您需要 2 张图像,1 张在左侧,1 张在右侧,每张占 50% 的宽度并放在屏幕底部。高度取决于您的需要,我目前硬编码高度 200 像素,但您可以将其更改为任何您想要的。
【解决方案2】:

您没有为图像提供垂直位置参考( top:x || bottom: x ),所以这可能就是您遇到这种行为的原因。

尝试在imgimgr 样式上设置bottom: 0,以便将它们设置到屏幕底部。

【讨论】:

  • 我删除了顶部/底部,因为它们没有效果,或者在设置为 0 时只是垂直居中图像。
  • 不要设置顶部:0,只是底部
  • 我更新了Snack,设置bottom让图片移到顶部
猜你喜欢
  • 1970-01-01
  • 2018-04-01
  • 2016-09-16
  • 1970-01-01
  • 2019-01-20
  • 2020-08-21
  • 2020-06-27
  • 1970-01-01
  • 2020-12-22
相关资源
最近更新 更多