Calculate image aspect ratio on load (#146)

* Calculate image aspect ratio on load

* Move aspect ratio bounds to constants
This commit is contained in:
Paul Frazee
2023-02-03 10:55:08 -06:00
committed by GitHub
parent cede0c772c
commit 2d1e38be72
+21 -3
View File
@@ -1,8 +1,12 @@
import React from 'react'
import {StyleProp, StyleSheet, TouchableOpacity, ViewStyle} from 'react-native'
import FastImage from 'react-native-fast-image'
import FastImage, {OnLoadEvent} from 'react-native-fast-image'
import {DELAY_PRESS_IN} from './constants'
import {LOADING} from '../../../lib/assets'
import {clamp} from '../../../../lib/numbers'
const MIN_ASPECT_RATIO = 0.33 // 1/3
const MAX_ASPECT_RATIO = 5 // 5/1
export function Image({
uri,
@@ -17,6 +21,16 @@ export function Image({
onPressIn?: () => void
style?: StyleProp<ViewStyle>
}) {
const [aspectRatio, setAspectRatio] = React.useState<number>(1)
const onLoad = (e: OnLoadEvent) => {
setAspectRatio(
clamp(
e.nativeEvent.width / e.nativeEvent.height,
MIN_ASPECT_RATIO,
MAX_ASPECT_RATIO,
),
)
}
return (
<TouchableOpacity
onPress={onPress}
@@ -24,7 +38,12 @@ export function Image({
onPressIn={onPressIn}
delayPressIn={DELAY_PRESS_IN}
style={[styles.container, style]}>
<FastImage style={styles.image} source={{uri}} defaultSource={LOADING} />
<FastImage
style={[styles.image, {aspectRatio}]}
source={{uri}}
defaultSource={LOADING}
onLoad={onLoad}
/>
</TouchableOpacity>
)
}
@@ -35,6 +54,5 @@ const styles = StyleSheet.create({
},
image: {
width: '100%',
aspectRatio: 1,
},
})