react-native – 使用React Native自动缩放图像高度
发布时间:2020-12-15 20:55:43 所属栏目:百科 来源:网络整理
导读:在我的React Native应用程序中,我从具有未知维度的API中获取图像。如果我知道所需的宽度,如何自动缩放高度? 例: 我将宽度设置为Dimensions.get(‘window’)。width。如何设置高度并保持相同的比例? export default class MyComponent extends Component
|
在我的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。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- swift – 获取堆上对象的大小(以字节为单位)
- c – 如何在常量时间内实现字符串pop_back?
- C / Boost ASIO中的内联ntohs()/ ntohl()
- vb实验
- Json.net[v3.5]对对象和JSON字符串的使用
- 在Flex4中使用RemoteObjectAMF0来连接fluorine网关
- 《deep learning》学习笔记(7)——深度学习中的正则化
- ruby-on-rails-3.1 – Rails 3.1资产无法识别rmagick上传的
- plsql – Oracle PL / SQL:PL / SQL中CLOB数据类型的性能
- c# – 使用ConfigurationManager帮助访问应用程序设置
