Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Get dimensions imperatively - RN Image, View #56

Open
sanjarcode opened this issue Dec 8, 2023 · 0 comments
Open

Get dimensions imperatively - RN Image, View #56

sanjarcode opened this issue Dec 8, 2023 · 0 comments

Comments

@sanjarcode
Copy link
Member

sanjarcode commented Dec 8, 2023

The Dimensions API is present but useful due to padding etc. Pretty non informative.

Image

https://stackoverflow.com/a/59801268

Image.resolveAssetSource(require('../myImage.png')).width

for network images - there's Image.getSize

View width height

https://stackoverflow.com/a/66870056

import React from 'react'
import { View } from 'react-native'

function MyComponent() {
  const onLayout=(event)=> {
    const {x, y, height, width} = event.nativeEvent.layout;
    
  }
  return (
    <View onLayout={onLayout}>
      <OtherComponent />
    </View>
  )
}

Usage example

import React, { useState } from "react";

import { Image, View, ScrollView, Text } from "react-native";

const myImage = require("../assets/images/SomeLocalImage.png");
const myImageDetails = Image.resolveAssetSource(myImage);

/**
 * Goal: render image as large as possible but without causing overflow
 *
 * Trying with local image
 */
export default function ImageTest() {
  const [multiplier, setMultiplier] = useState(1);
  return (
    <View style={{ flex: 1, paddingHorizontal: 16 }}>
      <ScrollView>
        <Text>Image trial</Text>
        <View
          // using layout to avoid hardcode padding calculation
          // just using this for getting `width`
          onLayout={(event) => {
            const { width } = event.nativeEvent.layout;
            if (multiplier === 1) setMultiplier(width / myImageDetails.width);
          }}
        />

        <Image
          source={myImage}
          style={{
            height: myImageDetails.height * multiplier,
            width: myImageDetails.width * multiplier,
          }}
        />
        <View>
          <Image
            source={myImage}
            style={{
              width: "100%",
              borderWidth: 1,
            }}
            resizeMode="contain"
          />
        </View>
      </ScrollView>
    </View>
  );
}
@sanjarcode sanjarcode changed the title Get dimensions imperatively - RN local image, View Get dimensions imperatively - RN Image, View Dec 8, 2023
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant