图像在反应本机中未居中



我有一个文件徽标.js如下:

import React, { Component } from 'react'
import { View, Image } from 'react-native'
const logo = () => (
<Image source = {{uri:'url_of_image'}}
style={{ width: 100, height: 100,justifyContent: 'center', alignItems: 'center'}}
/>
)
export default logo

我在应用程序中使用此文件.js作为:

import React from 'react';
import logo from './logo.js'
const App = () => {
return (
<logo />
)
}
export default App

我有两个问题。

  1. 我的图像出现在左上角,而我希望它出现在屏幕中央(水平和垂直)。为什么justifyContentalignItems不这样做呢?我需要做什么来解决这个问题?

  2. 我的图像目前只有 100 x 100 像素。我希望它看起来完全符合其实际大小或说 300*300,以较小者为准。我怎样才能做到这一点?谢谢。。。

编辑

我将徽标.js更改为:

...
const logo = () => (
<View style={styles.container}>
<Image source = {{uri:'url_of_image'}}
// style={{resizeMode: 'center'}}
//gives same result with above line comment/uncomment
/>
</View>
)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});

这样,我得到一个完全空白的屏幕。

在经历了重复的问题之后,我也尝试了这个:

...
const logo = () => (
<View style={styles.container}>
<Image source = {{uri:'url_of_image'}}
style={styles.logo}
/>
</View>
)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logo: {
width: 300,
height: 300,
},
});

我知道我已经硬编码了高度和宽度,但我只是专注于将其居中。它完全按照我想要的方式居中我的形象。因此,感谢您提及该链接。但是,我仍然无法做到 300 vs 本身的事情。请帮我弄清楚...

您可以使用Image.getSize来获取图像大小

下面是一个示例代码,

import React, {Component} from 'react';
import {
View,
Image,
} from 'react-native';
class App extends Component {
constructor() {
super();
this.state = { 
width: 300,
height: 300,
};
}
componentDidMount() {
Image.getSize('https://facebook.github.io/react/logo-og.png', (width, height) => { 
if (width < 300) this.setState({ width })
if (height < 300) this.setState({ height })
});
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Image source = {{uri:'https://facebook.github.io/react/logo-og.png'}}
style={{ width: this.state.width, height: this.state.height, justifyContent: 'center', alignItems: 'center'}}
/>
</View>
);
}
}
export default App;

希望对您有所帮助。

最新更新