RN Image resizeMode:'包含'奇怪的行为

时间:2017-01-29 23:44:11

标签: image react-native resize flexbox

我想在这样的行中获得带有图片和标题的标题: Desired result

使用此代码:

<View style={{ flex: 1, backgroundColor:'#ccf6c0', flexDirection:'column',}}>
      {/* ======================= HEADER ===================================*/}
      <View style={{flex: 0, flexDirection: 'row', backgroundColor:'#d5d5f7'}}>
         <Image
           source={require('./images/logo.png')}
           style={{resizeMode: 'contain', flex: 1}}
         />
         <View style={{flex: 1, justifyContent: 'center', backgroundColor:'#f7d5d5'}}>
           <Text style={{fontSize: 17, fontWeight:'bold', marginLeft: 7}}>
             Title
           </Text>
         </View>
       </View>
</View>

但我得到了这个输出:Wrong result - 图像上方和下方都有不必要的空间。

我在这里找不到想要得到的结果?

我的猜测:图像的原始大小为360x180(因此默认情况下它应该是768模拟器屏幕的一半宽度),但是Android接受它作为mdpi图像并升级到xhdpi(两个方向都是x2),然后使用它放大图像以计算容器高度。然后只有resizeMode:&#39;包含&#39;适用(在新的双高容器内)。 有什么建议?

2 个答案:

答案 0 :(得分:1)

这可能看起来像一个破碎的api,但这就是我在我的案子中解决它的方式:

<Image source={require('./images/logo.png')} 
       resizeMode='contain' 
       style={{flex:1, width: null, height: null}}/>

宽度和高度null看起来很奇怪,但这样你就可以摆脱静态大小并调整View的大小。

答案 1 :(得分:0)

在这种情况下唯一可行的解​​决方案是直接使用Dimensions来计算图像帧的硬设置大小,然后再调整图像大小:

...
import Image, Dimensions, StyleSheet from 'react-native';
...
const height = Dimensions.get('window').height;
...
const styles = StyleSheet.create({
  imageBox: {
    flex: 1,
    resizeMode: 'contain',
    width: width/2.12,
    height: width/4.24,
  },
  })
...
<Image
   source={require('./images/image.png')}
   style={styles.imageBox}
/>
相关问题