In my React Native app, I am fetching images from an API with unknown dimensions. How do I auto scale the height if I know my desired width?
Example:
I set t
You have 3 numbers :
and you should put "width of Screen" in width style and also calculate height for setup in style ??!!
componentWillMount() {
Image.getSize(this.props.product.image, (width, height) => {
const screenWidth = Math.round(Dimensions.get('window').width);
this.setState({screenWidth:screenWidth});
Calculatedheight = screenWidth * height / width ;
this.setState({Calculatedheight : Calculatedheight });
});
}
and
<Image
source={{uri: product.image,cache: 'only-if-cached'}}
style={{ height: this.state.screenHeight , width: this.state.Calculatedheight }}
/>
Here's some code I'm using in production. The backend user could make a logo image of any size and aspect ratio, but I needed the logo to fit an exact height with a max width. My self-scaling component is what resulted:
import React, { useState, useLayoutEffect, SFC } from "react";
import { Image } from "react-native";
import { Spinner } from "native-base";
interface INetworkImage {
targetHeight: number,
uri: string,
maxWidth: number
}
const NetworkImage: SFC<INetworkImage> = ({ uri, targetHeight, maxWidth }) => {
useLayoutEffect(() => setNaturalDimensions(uri), []);
const [imageWidth, setWidth] = useState(0);
const [imageHeight, setHeight] = useState(0);
const [scaleFactor, setScale] = useState(1);
function setNaturalDimensions(uri: string) {
Image.getSize(uri, (width: number, height: number) => {
if (width > maxWidth) {
// too wide case
setScale(maxWidth / width);
} else {
// scale to height case
setScale(targetHeight / height);
}
setWidth(width);
setHeight(height);
}, (error: any) => {
console.log("error", error);
});
}
function adjustView(e) {
if (e.nativeEvent.layout.width > maxWidth) {
setScale(scaleFactor * (maxWidth/e.nativeEvent.layout.width));
}
}
return (
imageHeight ?
<Image
onLayout={(e) => adjustView(e)}
source={{ uri: uri }}
style={{
width: imageWidth * scaleFactor,
height: imageHeight * scaleFactor,
resizeMode: "contain",
}}
/>:
<Spinner color='#454c7a' />
);
}
export default NetworkImage;
Then I use it by passing the uri, targetHeight, and maxwidth in as props:
export const deviceWidth = Dimensions.get("window").width;
<NetworkImage
uri={"https://purdyPic.com/image1"}
targetHeight={300}
maxWidth={deviceWidth * 0.85}
/>