在我的React Native应用程序中,我从具有未知维度的API中获取图像。如果我知道所需的宽度,如何自动缩放高度?
例:
我将宽度设置为Dimensions.get(‘window’)。width。如何设置高度并保持相同的比例?
- export default class MyComponent extends Component {
- constructor(props) {
- super(props)
- this.state = {
- imgUrl: 'http://someimg.com/coolstuff.jpg'
- }
- }
- componentDidMount() {
- // sets the image url to state
- this.props.getImageFromAPi()
- }
- render() {
- return (
- <View>
- <Image
- source={uri: this.state.imgUrl}
- style={styles.myImg}
- />
- <Text>Some description</Text>
- </View>
- )
- }
- }
- const styles = StyleSheet.create(
- myImg: {
- width: Dimensions.get('window').width,height: >>>???what goes here???<<<
- }
- )
尝试这个:
- import React,{ Component,PropTypes } from 'react';
- import { Image } from 'react-native';
- export default class ScaledImage extends Component {
- constructor(props) {
- super(props);
- this.state = {source: {uri: this.props.uri}};
- }
- componentWillMount() {
- Image.getSize(this.props.uri,(width,height) => {
- if (this.props.width && !this.props.height) {
- this.setState({width: this.props.width,height: height * (this.props.width / width)});
- } else if (!this.props.width && this.props.height) {
- this.setState({width: width * (this.props.height / height),height: this.props.height});
- } else {
- this.setState({width: width,height: height});
- }
- });
- }
- render() {
- return (
- <Image source={this.state.source} style={{height: this.state.height,width: this.state.width}}/>
- );
- }
- }
- ScaledImage.propTypes = {
- uri: PropTypes.string.isrequired,width: PropTypes.number,height: PropTypes.number
- };
我将URL作为名为uri的道具传递。您可以将宽度道具指定为Dimensions.get(‘window’)。宽度,应该覆盖它。
请注意,如果您知道要将高度设置为什么,并且需要调整宽度以保持比率,这也会起作用。在这种情况下,您可以指定高度支柱而不是宽度1。