9月11号 0.33版本,resizeMode中添加了center, 可以实现一样的功能。不过希望这篇文章还能帮助大家。
之前我们学习了从零学React Native之08Image组件
大家可以发现, 原生的Image控件无法实现等比放大后无丢失显示。
如: 有一张20x10的图片, 要放入一个40x30的显示区域内.
1. cover模式(默认),图片放大为60x30, 然后切成40x30, 会丢失部分显示的图片。
2. contain 模式, 图片分辨率为20x10, 四周都有空白。
3. stretch模式, 图片放大为40x30, 丢失原始的宽、高比。
但我们无法做到将图片放大为40*20, 然后再显示。接下来我们自定义组件ImageEquallyEnlarge:
import React, { Component } from 'react';
import {
Image
} from 'react-native';
export default class ImageEquallyEnlarge extends Component {
constructor(props) {
super(props);
this.state = {
style: {}
};
this.onImageLayout=this.onImageLayout.bind(this);
}
onImageLayout(event) {
let layout=event.nativeEvent.layout;
if(layout.width<=this.props.originalWidth) return;
if(layout.height<=this.props.originalHeight) return;
let originalAspectRatio=this.props.originalWidth/this.props.originalHeight;
let currentAspectRatio=layout.width/layout.height;
if(originalAspectRatio===currentAspectRatio) return;
if(originalAspectRatio>currentAspectRatio){
let newHeight=layout.width/originalAspectRatio;
this.setState({
style:{
height:newHeight
}
});
return ;
}
let newWidth=layout.height*originalAspectRatio;
this.setState({
style:{
width:newWidth
}
});
}
render(){
return(
<Image {...this.props}
style={[this.props.style,this.state.style]}
onLayout={this.onImageLayout}
/>
)
}
}
ImageEquallyEnlarge.prototype = {
originalWidth: React.PropTypes.number.isRequired,
originalHeight: React.PropTypes.number.isRequired
};
上面代码,没什么特殊的技巧, 我们都知道在组件开始布局或者布局改变的时候 就会调用组件的onLayout方法, 我们在onLayout方法中, 获取到了Image组件的实际宽高, 然后再根据传递过来图片真实的宽高计算下组件合适的宽高, 再通过状态机修改组件的宽高。
测试一下,修改index.android.js或者index.ios.js:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
Image
} from 'react-native';
import ImageEquallyEnlarge from './ImageEquallyEnlarge';
class AwesomeProject extends Component {
render() {
return (
<View style={styles.container}>
<ImageEquallyEnlarge
style={styles.imageStyle}
source={require('./image/big_star.png')}
originalHeight={70}
originalWidth={100}
/>
<ImageEquallyEnlarge
style={styles.image2Style}
source={require('./image/big_star.png')}
originalHeight={70}
originalWidth={100}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'blue'
},
imageStyle: {
width: 240,
height: 360,
backgroundColor: 'red'
},
image2Style: {
width: 300,
height: 460,
backgroundColor: 'red'
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
运行结果:

图片原图:

根据背景颜色就可以看到 图片实现了等比放大不丢失。
更多精彩请关注微信公众账号likeDev,公众账号名称:爱上Android。
