需求背景是給一個組件傳不同寬度的圖片,希望在顯示時能展示完整圖片,保持圖片位置、高度一致,寬度自適應
最開始給圖片統一設置了寬高,本以爲能像h5的img標籤一樣,自適應寬高還能左對齊
img: {
position: 'absolute',
top: 6,
left: 6,
height: 16,
width: 60,
resizeMode: 'cover',
},
結果發現比較寬的圖片能較好的展示,但是比較窄的圖片直接居中展示了
谷歌搜了一下,說contain是不支持設置向哪裏對齊的,默認就是取水平垂直居中的位置。因此對於需要適應不同寬度圖片的情況,需要手動根據圖片的寬高比計算出需要展示的實際寬度、高度,設置給image組件
官方給的例子如下,在componentDidMount時計算新的寬高,然後存放在state中
(個人感覺放在state中不太好,但是getSize方法是回調函數,不適合在render中調用,看來只能先這樣處理了)
// 官方示例 https://reactnative.cn/docs/0.51/image.html
var ImageSizeExample = React.createClass({
getInitialState: function() {
return {
width: 0,
height: 0,
};
},
componentDidMount: function() {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({width, height});
});
},
render: function() {
return (
<View style={{flexDirection: 'row'}}>
<Image
style={{
width: 60,
height: 60,
backgroundColor: 'transparent',
marginRight: 10,
}}
source={this.props.source} />
<Text>
Actual dimensions:{'\n'}
Width: {this.state.width}, Height: {this.state.height}
</Text>
</View>
);
},
});