我有一张图像,我希望其显示为设备屏幕的全宽。
仅使用 View 我就可以实现这一点:
<View style={{flex:1}}>
<Image resizeMode="contain" style={{flex: 1, height: undefined, width: undefined}} source={this.props.images.infoImage} />
</View>
将其更改为 ScrollView 会导致图像完全停止渲染:
<ScrollView style={{flex:1}}>
<Image resizeMode="contain" style={{flex: 1, height: undefined, width: undefined}} source={this.props.images.infoImage} />
</ScrollView>
我发现,如果我在图像上设置高度,它将呈现...但我希望图像能够动态响应设备的大小。
如何在不声明明确高度的情况下解决这个问题?
最佳答案
根据 @martinarroyo 的评论,我将 contentContainerStyle={{flex:1}}
添加到 ScrollView,如下所示:
<ScrollView contentContainerStyle={{flex:1}}>
<Image resizeMode="contain" style={{flex: 1, width: undefined, height: undefined}} source={this.props.images.infoImage} />
</ScrollView
这完全解决了我的问题。图像是显示屏的全宽,同时保持正确的宽高比。
编辑: 结果图像框架高度保持不变,但图像缩小。这意味着它的顶部和底部有大块的填充物。目前我还不知道如何删除它。
编辑2:
RN 似乎没有任何现成的工具,最终使用了 @Ihor Burlachenko 解决方案的修改版本。我创建了一个自定义组件,它采用所需的宽度/高度约束并根据该约束对其进行缩放。我需要将其用于本地文件,而 Image.getSize()
方法不起作用,因此我修改了 Ihor 的解决方案,通过传入包含宽度和高度的尺寸对象来实现此目的。
import React from 'react';
import { Image } from 'react-native';
export default class ScalableImage extends React.Component {
constructor(props) {
super(props);
this.state = {
width: null,
height: null,
}
}
componentDidMount() {
if(typeof this.props.source === 'string') {
Image.getSize(this.props.source, this._calculateImageDimensions, console.log);
} else if(this.props.dimensions) {
this._calculateImageDimensions(this.props.dimensions.width, this.props.dimensions.height)
}
}
render() {
return (
<Image
{ ...this.props }
style={[
this.props.style,
{ width: this.state.width, height: this.state.height }
]}
/>
);
}
_calculateImageDimensions(width, height) {
let ratio;
if (this.props.width && this.props.height) {
ratio = Math.min(this.props.width / width, this.props.height / height);
}
else if (this.props.width) {
ratio = this.props.width / width;
}
else if (this.props.height) {
ratio = this.props.height / height;
}
this.setState({ width: width * ratio, height: height * ratio });
}
}
ScalableImage.propTypes = {
width: React.PropTypes.number,
height: React.PropTypes.number,
dimensions: React.PropTypes.object
};
然后我这样使用它:
<ScalableImage source={require('../path/to/local/image.png')}
width={Dimensions.get('window').width()}
dimensions={{width: 700, height: 400}} />
关于javascript - 在 React Native ScrollView 中将图像缩小到设备宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42535819/