React-native 中 Image 组件中展示图片等比缩放的问题
1. 首先创建一个用于展示图片的组件,这里以ImageBox为例
只展示一个的话就占满屏幕,展示多个的话进行等比缩放
import React, { useState, useEffect } from 'react'
import { View, Image, StyleSheet } from 'react-native'
export default ImageBox = (props) => {
// count: 传递过来的图片的数量,决定展示的方式
// uri: 传递过来的图片的uri,这里已经加上了前缀 file://
// showWidth: 要展示的宽度,用一个就可以推出另一个了
const { count, uri, showWidth } = props
// 图片要展示的高度,默认是0
const [ showHeight, setShowHeight] = useState( 0 )
useEffect( () => {
if(uri) {
Image.getSize( uri, ( w, h ) => {
// 根据传递的过来的宽度,计算图片的高度
setShowHeight(h * showWidth / w)
} )
}
})
return (
// 这里的样式是为了在展示多个图片的时候,图片之间有留白,
// 使用 View 标签嵌套的原因是因为后期可以在 View 标签里面添加另外的标签,用于对图片的操作
<View style = { [ count > 1 ? styles.container : '', { width: showWidth, height: showHeight } ] }>
<Image source = {{uri}} style = {{ flex: 1 }}
></Image>
</View>
)
}
const styles = StyleSheet.create({
container: {
marginLeft: 10,
marginTop: 10
},
})
2.在需要用于展示图片的组件中调用
这里定义了一个函数,接收一个图片路径数组
function createImage(imagePathArr) {
if( imagePathArr.length > 1 ) {
return imagePathArr.map( imagePath => {
return <ImageBox key = { imagePath.uri } count = { imagePathArr.length } uri = { imagePath.uri } showWidth = {( width - 40 ) / 3 } />
} )
}else {
return <ImageBox count = { 1 } uri = { imagePathArr[0].uri } showWidth = {width} />
}
}
在组件中你可以这样使用 imagePathArr
是你的图片路径数组
...
export default MyImage = () => {
...
return(
<ScrollView>
...
{ createImage(imagePathArr) }
...
</ScrollView>
)
}
3.注意:在 { createImage(imagePathArr) }
的父容器中应该有必要样式
**关于为什么样式拆分和使用 contentContainerStyle
**,这是因为在 ScrollView
组件中用 style
定义的样式不能有 justifyContent
alignItems
,需要用 contentContainerStyle
,或许以后会支持
<ScrollView contentContainerStyle = { styles.scrollBox1 } style = { styles.scrollBox2 }>
...
{ createImage(imagePathArr) }
...
</ScrollView>
// --------------------------------------------
const styles = StyleSheet.create({
scrollBox1: {
flexDirection: 'row',
flexWrap: 'wrap',
alignContent: 'flex-start',
},
scrollBox2: {
flex: 1,
backgroundColor: '#fff'
},
})