Calculate image aspect ratio on load (#146)
* Calculate image aspect ratio on load * Move aspect ratio bounds to constants
This commit is contained in:
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user