如何在React Native中将一个图像居中放在另一个图像上

时间:2018-01-05 13:29:58

标签: react-native

我正在尝试在React Native中制作带有面部图像和以时钟为中心的针的时钟组件。  不允许嵌入其他图像。 我找到了一些帖子,用于将文本居中放在图像上,但无法找到任何方法将图像居中放在图像上。

编辑: 我试图找到一种避免给出绝对位置的方法,这样组件就可以动态调整大小。

2 个答案:

答案 0 :(得分:4)

如果我理解正确,您希望在其他图像上显示一张图像。使用一个作为父图像而另一个作为子图像而不使用绝对位置。 为此,您可以使用react-native提供的 ImageBackground 组件,并使用百分比值设置其高度和宽度。

以下是示例:

父图片:Clock.png是 ImageBackground 组件

子图片:Needle.png是图片组件

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

export default class ImageView extends Component {
  render() {
    return (
      <View
        style={{
          flex: 1
        }}
      >
        <View
          style={{
            flex: 0.25,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'red'
          }}
        >
          <Text style={{ color: 'white', fontSize: 26 }}>I am Header</Text>
        </View>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            // backgroundColor: 'blue',
            borderWidth: 1,
            borderColor: 'red'
          }}
        >
          <ImageBackground
            source={require('@assets/Clock.png')}
            style={{
              height: '60%',
              width: '100%'
            }}
            resizeMode="contain"
          >
            <Image
              style={{
                marginTop: '4.5%',
                alignSelf: 'center',
                height: '30%',
                width: '100%'
              }}
              resizeMode="contain"
              source={require('@assets/Needle.png')}
            />
          </ImageBackground>
        </View>
      </View>
    )
  }
}

Clock

答案 1 :(得分:0)

与常规旧的html,css。

中处理相同

使用position:absolute然后对齐项目,使其符合您的预期。

相关问题