主要代码
- 获取图片宽高比后计算实际宽高。需要根据basic不同,分别计算不同情况下的宽高。basic具体看完整代码。
basicWidth = () => {
let imgInfo = {};
if (this.props.source.uri) {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: this.props.width,
height: this.props.width * (height / width)
});
});
} else {
imgInfo = Image.resolveAssetSource(this.props.source);
this.setState({
width: this.props.width,
height: this.props.width * (imgInfo.height / imgInfo.width)
});
}
};
basicHeight = () => {
let imgInfo = {};
if (this.props.source.uri) {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: this.props.height * (width / height),
height: this.props.height
});
});
} else {
imgInfo = Image.resolveAssetSource(this.props.source);
this.setState({
width: this.props.height * (imgInfo.width / imgInfo.height),
height: this.props.height
});
}
};
<Image
resizeMode="stretch"
source={this.props.source}
style={[this.props.style, {
width: this.state.width,
height: this.state.height
}]}
/>
完整源码
import React from 'react';
import {Image} from 'react-native';
import PropTypes from 'prop-types';
//这里获取的是屏幕的宽高
import {getScreenWidth, getScreenHeight} from '../../utils/util';
export default class AdaptorImg extends React.Component {
static defaultProps = {
width: getScreenWidth(),
height: getScreenHeight(),
basic: 'width'
};
static propTypes = {
width: PropTypes.number,
height: PropTypes.number,
source: PropTypes.any,
basic: PropTypes.oneOf(['height', 'width']) //配合上面的width或者height使用
};
constructor(props) {
super(props);
this.state = {
width: 0,
height: 0
};
init();
}
init = async () => {
let {basic} = this.props;
if (basic === 'width') {
this.basicWidth();
} else {
this.basicHeight();
}
};
basicWidth = () => {
let imgInfo = {};
if (this.props.source.uri) {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: this.props.width,
height: this.props.width * (height / width)
});
});
} else {
imgInfo = Image.resolveAssetSource(this.props.source);
this.setState({
width: this.props.width,
height: this.props.width * (imgInfo.height / imgInfo.width)
});
}
};
basicHeight = () => {
let imgInfo = {};
if (this.props.source.uri) {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: this.props.height * (width / height),
height: this.props.height
});
});
} else {
imgInfo = Image.resolveAssetSource(this.props.source);
this.setState({
width: this.props.height * (imgInfo.width / imgInfo.height),
height: this.props.height
});
}
};
render() {
return (
<Image
resizeMode="stretch"
source={this.props.source}
style={[this.props.style, {
width: this.state.width,
height: this.state.height
}]}
/>
);
}
}
- 原文 https://blog.csdn.net/qq_38545425/article/details/121920514