candlefinance / faster-image

Fast image loading for React Native backed by performant native libraries.
https://candle.fi/discord
MIT License
596 stars 28 forks source link

Dealing with dynamically sized images #54

Closed cyberixae closed 2 months ago

cyberixae commented 2 months ago

I'm wondering how to deal with dynamically sized images when using faster-image. Does faster-image have something similar to the Image.getSize( ) utility that ships with React Native? Can I combine the two or does that result in the image being downloaded twice, first by react-native, and then again by faster-image?

tconns commented 2 months ago

@cyberixae Please use the following code: ... onSuccess={(e) => console.log('success', e.nativeEvent.height, e.nativeEvent.width)}

This size will be returned after the image is successfully loaded and also retrieved from the cache. It works on both Android and iOS. There will be no repeated downloads if you have configured the cache. If you need to use it globally, store it in a Cache object for reuse

Example:

interface ImageSize { width: number; height: number; }

class ImageSizeCache { private cache: Map<string, ImageSize>;

constructor() { this.cache = new Map<string, ImageSize>(); }

set(url: string, size: ImageSize): void { this.cache.set(url, size); }

get(url: string): ImageSize | undefined { return this.cache.get(url); }

has(url: string): boolean { return this.cache.has(url); } }

const imageSizeCache = new ImageSizeCache();

... onSuccess={(e) => {

const { height, width, source } = e.nativeEvent

console.log('success', height, width, source)

imageSizeCache.set(source, { height, width })

}}