Created
May 22, 2021 10:32
-
-
Save pplytas/8adf3c61d4178631062cba821584f847 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useMemo } from 'react'; | |
import { Image } from 'react-native'; | |
const createMissingDimensionStyle = (source, style) => { | |
const { width, height } = Image.resolveAssetSource(source); | |
const aspectRatio = width / height; | |
if (style.width) return { height: style.width / aspectRatio }; | |
if (style.height) return { width: style.height * aspectRatio }; | |
return {}; | |
}; | |
const ScalableImage = ({ source, style, ...rest }) => { | |
// Merge array of styles into a single object | |
if (Array.isArray(style)) style = Object.assign({}, ...style); | |
// Memoize calculations | |
const missingDimensionStyle = useMemo(() => | |
createMissingDimensionStyle(source, style), | |
[source, style] | |
); | |
return <Image style={[style, missingDimensionStyle]} source={source} {...rest} />; | |
}; | |
export default ScalableImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment