2017-07-19 148 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); 
    }; 
} 

這將更新圖像的尺寸以匹配屏幕的寬度。

相關問題