react-native – 使用React Native自动缩放图像高度

前端之家收集整理的这篇文章主要介绍了react-native – 使用React Native自动缩放图像高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的React Native应用程序中,我从具有未知维度的API中获取图像。如果我知道所需的宽度,如何自动缩放高度?

例:

我将宽度设置为Dimensions.get(‘window’)。width。如何设置高度并保持相同的比例?

  1. export default class MyComponent extends Component {
  2. constructor(props) {
  3. super(props)
  4. this.state = {
  5. imgUrl: 'http://someimg.com/coolstuff.jpg'
  6. }
  7. }
  8.  
  9. componentDidMount() {
  10. // sets the image url to state
  11. this.props.getImageFromAPi()
  12. }
  13.  
  14. render() {
  15. return (
  16. <View>
  17. <Image
  18. source={uri: this.state.imgUrl}
  19. style={styles.myImg}
  20. />
  21. <Text>Some description</Text>
  22. </View>
  23. )
  24. }
  25. }
  26.  
  27. const styles = StyleSheet.create(
  28. myImg: {
  29. width: Dimensions.get('window').width,height: >>>???what goes here???<<<
  30. }
  31. )
尝试这个:
  1. import React,{ Component,PropTypes } from 'react';
  2. import { Image } from 'react-native';
  3.  
  4. export default class ScaledImage extends Component {
  5. constructor(props) {
  6. super(props);
  7. this.state = {source: {uri: this.props.uri}};
  8. }
  9.  
  10. componentWillMount() {
  11. Image.getSize(this.props.uri,(width,height) => {
  12. if (this.props.width && !this.props.height) {
  13. this.setState({width: this.props.width,height: height * (this.props.width / width)});
  14. } else if (!this.props.width && this.props.height) {
  15. this.setState({width: width * (this.props.height / height),height: this.props.height});
  16. } else {
  17. this.setState({width: width,height: height});
  18. }
  19. });
  20. }
  21.  
  22. render() {
  23. return (
  24. <Image source={this.state.source} style={{height: this.state.height,width: this.state.width}}/>
  25. );
  26. }
  27. }
  28.  
  29. ScaledImage.propTypes = {
  30. uri: PropTypes.string.isrequired,width: PropTypes.number,height: PropTypes.number
  31. };

我将URL作为名为uri的道具传递。您可以将宽度道具指定为Dimensions.get(‘window’)。宽度,应该覆盖它。

请注意,如果您知道要将高度设置为什么,并且需要调整宽度以保持比率,这也会起作用。在这种情况下,您可以指定高度支柱而不是宽度1。

猜你在找的React相关文章