首页 文章

React Native Image绝对定位

提问于
浏览
0

我试图在底部边框处定位图像,每边都有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,
    }
});

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

2 回答

  • 0

    你没有给你的图像一个垂直位置参考(顶部:x || bottom:x),所以这可能是你遇到这种行为的原因 .

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

  • 0

    要实现您的要求,请使用 flexDirection: 'row' 将2个图像包装到 View ,然后使用 justityContent: 'flex-end' 创建顶级 View .

    我做了一个简单的代码,硬编码高度为200像素,并将背景设置为 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',
        }
    });
    

相关问题