2017-07-19 147 views
2

我是反应原生的新手。 我想要做的是适合设备中的图像,并保持图像的比例。只是我想使width : 100%React Native - 如何使图像宽度100%和垂直顶部?

我搜索了如何使它,似乎resizeMode = 'contain'是很好的。

但是,由于我使用了resizeMode = 'contain',图像保持了我不想要的垂直居中的位置。 我希望它是垂直顶部。

我试图使用插件,如react-native-fit-image,但没有运气。

而我发现the reason why the image is not sizing automatically。 但我仍然不知道如何做到这一点。

所以,我的问题是处理这种情况的最好方法是什么?

我必须手动将width, height大小的每个图像?

我想:

  • 保持图像的比例。
  • 垂直顶部定位。

阵营本地测试代码:

https://snack.expo.io/ry3_W53rW

最后,我想做出什么:

https://jsfiddle.net/hadeath03/mb43awLr/

感谢。

+0

看看[react-native-scalable-image](https://www.npmjs.com/package/react-native-scalable-image) –

回答

2

图像垂直居中,因为您已将flex: 1添加到样式属性。不要添加flex:1,因为这会将图像填充到其父项,在这种情况下不需要。

您应该始终在React Native中的图像上添加高度和宽度。如果图像始终相同,则可以使用Dimensions.get('window').width来计算图像的大小。例如,如果比例始终为16x9,则高度为图像宽度的9/16。宽度等于装置宽度,所以:

const dimensions = Dimensions.get('window'); 
const imageHeight = Math.round(dimensions.width * 9/16); 
const imageWidth = dimensions.width; 

return (
    <Image 
    style={{ height: imageHeight, width: imageWidth }} 
    /> 
); 

注:当使用像这样的实现,您的图像不会自动旋转你的设备时,使用分屏,等你将不得不采取这些照顾调整动作以及如果你支持多个方向...

如果比例不相同,动态更改9/16的比例为每个不同的图像。如果你真的不打扰图像有点裁剪,您可以使用覆盖模式与固定高度,以及:(https://snack.expo.io/rk_NRnhHb

<Image 
    resizeMode={'cover'} 
    style={{ width: '100%', height: 200 }} 
    source={{uri: temp}} 
/> 
+0

感谢您的回答。 所以我必须知道图像大小并使用Dimensions来控制图像大小。 –

+0

在你的博览会的例子中,你为什么要放宽度:'100%'? 我不认为它的工作。 –

+0

100%仅适用于较新版本的React Native(如果我没有错误,则从0.43开始) – dejakob

0

只给这一个镜头,以及

你也可以等待Image onLayout回调来获取其布局属性并使用它来更新维度。我为此创建了一个组件:

import * as React from 'react'; 
import { Dimensions, Image, ImageProperties, LayoutChangeEvent, StyleSheet, ViewStyle } from 'react-native'; 

export interface FullWidthImageState { 
    width: number; 
    height: number; 
    stretched: boolean; 
} 

export default class FullWidthImage extends React.Component<ImageProperties, FullWidthImageState> { 
    constructor(props: ImageProperties) { 
    super(props); 

    this.state = { width: 100, height: 100, stretched: false }; 
    } 

    render() { 
    return <Image {...this.props} style={this.getStyle()} onLayout={this.resizeImage} />; 
    } 

    private resizeImage = (event: LayoutChangeEvent) => { 
    if (!this.state.stretched) { 
     const width = Dimensions.get('window').width; 
     const height = width * event.nativeEvent.layout.height/event.nativeEvent.layout.width; 
     this.setState({ width, height, stretched: true }); 
    } 
    }; 

    private getStyle =(): ViewStyle => { 
    const style = [StyleSheet.flatten(this.props.style)]; 
    style.push({ width: this.state.width, height: this.state.height }); 
    return StyleSheet.flatten(style); 
    }; 
} 

这将更新图像的尺寸以匹配屏幕的宽度。

相关问题