在视图中使用未知大小调整React-Native Image大小

时间:2017-03-20 04:48:45

标签: android ios reactjs react-native jsx

React-Naive建议开发人员在运行前说明图像维度。我知道这是一个很好的做法。我的问题是......如果我想将<Image>调整为宽度未知的包含<View>的相同宽度,怎么样?

例如,<Image><View> rowDirection: 'row', flex: 0.8 resizeMode。在不同的设备中,我有不同的屏幕宽度。我怎么知道80%设备的实际宽度?

P.S。我已经尝试了所有<View style={{ flexDirection: 'row', flex: 1, backgroundColor: '#CCF' }}> <Image source={require('../resources/images/side-menu-header.png')} style={{ width: null, height: null, flex: 0.8 }} /> <View style={{ flex: 0.2 }} /> </View> 但没有运气。

任何人都可以帮助我谢谢!

更新1

我试过这个片段

resizeMode

Result image of above code

但是,是的,此图像现在设置为0.8宽度,但其中一些区域已被裁剪。这不是我想要的。因此,我将其contain设置为<View style={{ flexDirection: 'row', flex: 1, backgroundColor: '#CCF' }}> <Image resizeMode='contain' source={require('../resources/images/side-menu-header.png')} style={{ width: null, height: null, flex: 0.8 }} /> <View style={{ flex: 0.2 }} /> </View> ,如下面的代码段

 function car(gas, mpg) {
    this.gas = gas;
    if (this.gas <= 0){this.empty = true;}
    else{this.empty = false;}
    this.mpg = mpg;
    //this.range = gas * mpg;
    //this.empty = empty;

    this.drive = function (miles) {
    this.gas -= miles/this.mpg;
    if(this.gas <=0) {
    this.empty = true;
    }else{
     this.empty = false;
     }
    };

    this.fill = function (gallons){
    if (this.gas <=0) {
    this.fill = false;}
    else{this.fill = true;}
    };
    }

Result image of above code

这不是我的预期!如您所见,图像现在变为0.8宽度并显示整个图像,但顶部和底部空间由其原始尺寸占据。 (原始图像尺寸很大)

我想我可以用几句话简化这个问题:如何在我的应用中显示全宽图像?我无法将其宽度设置为1080,因为并非所有设备都具有1080像素的宽度。

3 个答案:

答案 0 :(得分:1)

使用Dimensions API使图像尺寸动态化。

示例代码:

const { width, height } = Dimensions.get('window');
<Image
    source={{uri: `${url}`}}
    style={{ width: width * 0.8, height: height * 0.8 }}
/>

宽度* 0.8和高度* 0.8 分别是屏幕尺寸宽度和高度的80%。

答案 1 :(得分:0)

widthheight null传递给style道具,如下所示:

<Image resizeMode='cover' source={{ uri: 'image.png' }} style={{ width: null, height: null, flex: 0.8 }} />

答案 2 :(得分:0)

就我而言,你需要的是获得设备大小的API。

尝试尺寸,使用如下:

&#13;
&#13;
let {height, width} = Dimensions.get('window');
&#13;
&#13;
&#13;