2017-07-01 96 views
0

我想要縮放圖像以填充父容器的寬度,同時保持寬高比。水平居中圖像,而不是垂直

這是代碼:

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

export default class App extends React.Component { 
    render() { 
    return (
     <View style={styles.container}> 
     <Image style={styles.bgContainer} resizeMode='contain' source={require('./app/images/green.png')} /> 
     <Text>text</Text> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    backgroundColor: '#fff', 
    flexDirection:'column', 
    }, 
    bgContainer: { 
    flex: 1, 
    width: null, 
    height: null, 
    justifyContent: 'flex-start', 
    } 
}); 

這是我的結果:

enter image description here

我不想圖片佔用更多的空間,它的縮放高度,我想結果要這樣:

enter image description here

+0

你試過了嗎:'aspectRatio:1'? – Cherniv

+0

aspectRatio在反應本機不工作 –

+0

@MeysamIzadmehr我們在談論同樣的事情嗎? http://facebook.github.io/react-native/releases/0.44/docs/layout-props.html#aspectratio – Cherniv

回答

0

更新

作爲@Cherniv評論,使用aspectRatio: 1就夠了。所以,沒有必要手動計算它。只需將它添加到bgContainer即可。

您加入flex: 1到圖像。父母的唯一孩子是flex: 1。所以它涵蓋了整個家長。首先,移除flex。設置圖像的高寬比,並使用屏幕寬度生成圖像相對高度:

import React from 'react'; 
import { StyleSheet, Text, View, Image,Dimensions } from 'react-native'; 
const { width } = Dimensions.get('window'); 

export default class App extends React.Component { 
    render() { 
    return (
     <View style={styles.container}> 
     <Image style={styles.bgContainer} resizeMode='contain' source={require('./app/images/green.png')} /> 
     <Text>text</Text> 
     </View> 
    ); 
    } 
} 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    backgroundColor: '#fff', 
    flexDirection:'column', 
    }, 
    bgContainer: { 
    width: width, 
    height: imageHeight * width/imageWidth, // imageHeight & imageWidth are from your image pixel dimensions 
    justifyContent: 'flex-start', 
} 
});