1.0.0 • Published 3 years ago

killi8n-react-native-fast-image v1.0.0

Weekly downloads
-
License
(MIT AND Apache-2...
Repository
github
Last release
3 years ago

Performant React Native image component.

Version Downloads Build Status Code Coverage

Watch on GitHub Star on GitHub Tweet

React Native's Image component handles image caching like browsers for the most part. If the server is returning proper cache control headers for images you'll generally get the sort of built in caching behavior you'd have in a browser. Even so many people have noticed:

  • Flickering.
  • Cache misses.
  • Low performance loading from cache.
  • Low performance in general.

FastImage is an Image replacement that solves these issues. FastImage is a wrapper around SDWebImage (iOS) and Glide (Android).

Features

  • Aggressively cache images.
  • Add authorization headers.
  • Prioritize images.
  • Preload images.
  • GIF support.
  • Border radius.

Usage

Note: You must be using React Native 0.60.0 or higher to use the most recent version of react-native-fast-image.

yarn add react-native-fast-image
import FastImage from 'react-native-fast-image'

const YourImage = () => (
    <FastImage
        style={{ width: 200, height: 200 }}
        source={{
            uri: 'https://unsplash.it/400/400?image=1',
            headers: { Authorization: 'someAuthToken' },
            priority: FastImage.priority.normal,
        }}
        resizeMode={FastImage.resizeMode.contain}
    />
)

Are you using Glide already using an AppGlideModule?

Are you using Proguard?

If you use Proguard you will need to add these lines to android/app/proguard-rules.pro:

-keep public class com.dylanvann.fastimage.* {*;}
-keep public class com.dylanvann.fastimage.** {*;}
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

Properties

source?: object

Source for the remote image to load.


source.uri?: string

Remote url to load the image from. e.g. 'https://facebook.github.io/react/img/logo_og.png'.


source.headers?: object

Headers to load the image with. e.g. { Authorization: 'someAuthToken' }.


source.priority?: enum

  • FastImage.priority.low - Low Priority.
  • FastImage.priority.normal (Default) - Normal Priority.
  • FastImage.priority.high - High Priority.

source.cache?: enum

  • FastImage.cacheControl.immutable - (Default) - Only updates if url changes.
  • FastImage.cacheControl.web - Use headers and follow normal caching procedures.
  • FastImage.cacheControl.cacheOnly - Only show images from cache, do not make any network requests.

resizeMode?: enum

  • FastImage.resizeMode.contain - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.cover (Default) - Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).
  • FastImage.resizeMode.stretch - Scale width and height independently, This may change the aspect ratio of the src.
  • FastImage.resizeMode.center - Do not scale the image, keep centered.

onLoadStart?: () => void

Called when the image starts to load.


onProgress?: (event) => void

Called when the image is loading.

e.g. onProgress={e => console.log(e.nativeEvent.loaded / e.nativeEvent.total)}


onLoad?: (event) => void

Called on a successful image fetch. Called with the width and height of the loaded image.

e.g. onLoad={e => console.log(e.nativeEvent.width, e.nativeEvent.height)}


onError?: () => void

Called on an image fetching error.


onLoadEnd?: () => void

Called when the image finishes loading, whether it was successful or an error.


style

A React Native style. Supports using borderRadius.


fallback: boolean

If true will fallback to using Image. In this case the image will still be styled and laid out the same way as FastImage.


tintColor?: number | string

If supplied, changes the color of all the non-transparent pixels to the given color.

Static Methods

FastImage.preload: (source[]) => void

Preload images to display later. e.g.

FastImage.preload([
    {
        uri: 'https://facebook.github.io/react/img/logo_og.png',
        headers: { Authorization: 'someAuthToken' },
    },
    {
        uri: 'https://facebook.github.io/react/img/logo_og.png',
        headers: { Authorization: 'someAuthToken' },
    },
])

Troubleshooting

If you have any problems using this library try the steps in troubleshooting and see if they fix it.

Development

Follow these instructions to get the example app running.

Supported React Native Versions

This project only aims to support the latest version of React Native.\ This simplifies the development and the testing of the project.

If you require new features or bug fixes for older versions you can fork this project.

Credits

The idea for this modules came from vovkasm's react-native-web-image package. It also uses Glide and SDWebImage, but didn't have some features I needed (priority, headers).

Thanks to @mobinni for helping with the conceptualization

Licenses

  • FastImage - MIT © DylanVann
  • SDWebImage - MIT
  • Glide - BSD, part MIT and Apache 2.0. See the LICENSE file for details.
abort-controllerabababbrevJSONStreamacceptsabsolute-pathacorn-globalsacornacorn-jsxacorn-walkagent-baseadd-streamagentkeepaliveansi-colorsaggregate-erroransi-cyanansi-alignajvansi-fragmentsansi-escapesansi-grayansi-regexansi-redansi-wrapansi-stylesansicolorsansistylesare-we-there-yetargparseanymatchaprobaarchyaria-queryargv-formatterarr-diffarr-flattenarr-unionarray-filterarray-equalarray-maparray-find-indexarray-ifyarray-slicearray-includesarray-reducearray-unionarray-uniquearray.prototype.flatartarray.prototype.flatmaparrifyasapasn1astral-regexassign-symbolsassert-plusast-types-flowasync-eachasyncasync-limiterasynckitat-least-nodeatobaws-sign2aws4axe-coreaxobject-querybabel-plugin-dynamic-import-nodebabel-plugin-jest-hoistbabel-plugin-emotionbabel-plugin-syntax-jsxbabel-plugin-macrosbabel-plugin-istanbulbabel-plugin-syntax-trailing-function-commasbabel-preset-jestbabel-preset-fbjsbalanced-matchbasic-authbasebash-pathbash-globbcrypt-pbkdfbefore-after-hookbig-integerbase64-jsbin-linksbinary-extensionsblorkbindingsbluebirdboxenbottleneckbrace-expansionbracesbplist-creatorbplist-parserbrowser-process-hrtimebserbrowserslistbuffer-crc32browser-resolvebuffer-frombylinebuiltinsbuiltin-modulesbyte-sizebytescache-basecall-limitcaller-callsitecacachecaller-pathcallsitescamelcasecamelcase-keyscapture-exitcaniuse-litecardinalcapture-stack-tracecaselesschownrci-infochalkchokidarchardetcidr-regexclass-utilsclean-stackcli-boxescli-cursorcli-columnscli-spinnerscli-tablecli-table3cli-widthclonecmd-shimcliuicocollection-visitcolor-convertcode-point-atcolor-namecolorettecolor-supportcolorscommandercolumnifycombined-streamcommand-existscomponent-emittercommondircompare-funccompressioncompressibleconcat-mapconcat-streamconfig-chainconfigstoreconnectconfusing-browser-globalsconsole-control-stringscontains-pathconventional-changelogconventional-changelog-cliconventional-changelog-atomconventional-changelog-angularconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-codemirrorconventional-changelog-emberconventional-changelog-expressconventional-changelog-eslintconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-jqueryconventional-changelog-writerconventional-commits-filterconventional-commits-parsercopy-concurrentlyconvert-source-mapcore-js-purecopy-descriptorcore-jscore-js-compatcreate-react-classcore-util-iscreate-error-classcross-spawncosmiconfigcssomcrypto-random-stringcssstylecurrently-unhandledcyclistcsstypedamerau-levenshteindata-urlsdashdashdargsdateformatdebugdebuglogdayjsdecamelizedecamelize-keysdecode-uri-componentdeep-freezedeep-isdeep-extenddeepmergedefine-propertydefaultsdefine-propertiesdelayed-streamdelegatesdepddeprecationdenodeifydestroydetect-indentdezalgodetect-newlinedidyoumeandiff-sequencesdir-globdoctrinedotenvdot-propdomexceptionduplexer2duplexer3duplexifyeach-parallel-asyncecc-jsbnee-firsteditoremoji-regexelectron-to-chromiumend-of-streamencodingencodeurlenv-cienv-pathserr-codeenvinfoerror-exes-abstractes-to-primitiveerrnoerrorhandleres6-promisees6-promisifyescaladeescodegenescape-htmlescape-string-regexpeslinteslint-config-react-appeslint-import-resolver-nodeeslint-module-utilseslint-plugin-jsx-a11yeslint-plugin-importeslint-plugin-reacteslint-plugin-flowtypeeslint-plugin-react-hookseslint-scopeeslint-visitor-keyseslint-utilsespreeesprimaesrecurseesqueryestraverseesutilsetagevent-target-shimexitexec-sheventemitter3execaexpectexpand-bracketsestree-walkerextendextend-shallowexternal-editorextglobfancy-logfast-globfast-deep-equalextsprintffast-json-stable-stringifyfast-levenshteinfbjs-css-varsfb-watchmanfastqfbjsfiggy-puddingfbjs-scriptsfiguresfile-entry-cachefill-rangefile-uri-to-pathfind-cache-dirfind-upfinalhandlerfind-npm-prefixfind-yarn-workspace-rootfind-rootfind-versionsflat-cacheflattedfor-inform-datafragment-cacheforever-agentfreshfrom2fs-extraflush-write-streamfs-readdir-recursivefs-minipassfs-vacuumfs-write-stream-atomicfseventsfs.realpathfunction-bindfunctional-red-black-treegaugegenfungentle-fsgensyncget-caller-fileget-pkg-repoget-stdinget-streamget-valuegetpassgit-hooks-listgit-log-parsergit-remote-origin-urlgit-raw-commitsgitconfiglocalglobglob-parentglobalsglobal-dirsgit-semver-tagsglobbygraceful-fsgrowlyhar-schemagothandlebarshar-validatorhard-rejectionhashas-flaghas-unicodehas-symbolshas-valuehas-valueshook-stdhosted-git-infohermes-enginehtml-encoding-snifferhttp-errorshttp-cache-semanticshtml-escaperhttp-proxy-agenthttps-proxy-agenthttp-signaturehuman-signalshumanize-msiconv-liteignoreiferrimage-sizeignore-walkimport-freshimport-fromimport-lazyimport-localimurmurhashindent-stringinfer-ownerinflightinheritsinquirerinit-package-jsoniniinternal-slotinterpretinvariantinto-streaminvert-kvipip-regexis-accessor-descriptoris-arrayishis-binary-pathis-bufferis-callableis-ciis-cidris-date-objectis-data-descriptoris-descriptoris-directoryis-finiteis-extendableis-extglobis-generator-fnis-globis-moduleis-fullwidth-code-pointis-installed-globallyis-npmis-numberis-objis-path-insideis-redirectis-plain-objis-plain-objectis-referenceis-promiseis-regexis-retry-allowedis-streamis-stringis-text-pathis-symbolis-windowsis-typedarrayis-utf8is-wslisexeisarrayisobjectisomorphic-fetchissue-parseristanbul-lib-coverageistanbul-lib-reportistanbul-lib-instrumentisstreamjava-propertiesistanbul-reportsjest-changed-filesjest-clijest-configistanbul-lib-source-mapsjest-docblockjest-diffjest-eachjest-environment-jsdomjest-environment-nodejest-jasmine2jest-leak-detectorjest-get-typejest-haste-mapjest-message-utiljest-matcher-utilsjest-resolvejest-mockjest-pnp-resolverjest-resolve-dependenciesjest-regex-utiljest-runnerjest-runtimejest-serializerjest-snapshotjest-validatejest-utiljest-workerjest-watcherjetifierjs-yamljs-tokensjsbnjsc-androidjsdomjson-parse-better-errorsjsescjson-schemajson-stable-stringifyjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonparsejsonfilejsonifyjsprimjsx-ast-utilskind-ofklawkleurlanguage-tagslatest-versionlcidlanguage-subtag-registrylazy-propertyleft-padlevenlevnlevenarylibnpmlibcipmlibnpmaccesslibnpmconfiglibnpmsearchlibnpmpublishlibnpmhooklibnpmorglibnpmteamlibnpxload-json-filelines-and-columnslocate-pathlock-verifylockfilelodash._baseuniqlodash._reinterpolatelodash.capitalizelodashlodash._rootlodash._createsetlodash.clonedeeplodash.ismatchlodash.escaperegexplodash.isplainobjectlodash.sortbylodash.templatelodash.isstringlodash.templatesettingslodash.throttlelodash.toarraylodash.unionlodash.uniqlodash.withoutlodash.uniqbylog-symbolslogkittyloose-envifylru-cachelowercase-keysloud-rejectionmagic-stringmake-dirmacos-releasemake-fetch-happenmakeerrormap-cachemap-age-cleanermarkedmap-visitmarked-terminalmap-objmeantmeowmerge-streammemmerge2metrometro-babel-registermetro-cachemetro-babel-transformermetro-configmetro-inspector-proxymetro-coremetro-react-native-babel-transformermetro-minify-uglifymetro-resolvermetro-source-mapmetro-symbolicatemicromatchmimemime-dbmimic-fnmin-indentminimatchmime-typesminimistminimist-optionsminipassminizlibmississippimixin-deepmkdirpmorganmodify-valuesmove-concurrentlynanmsmute-streamnatural-comparenanomatchnegotiatorneo-asyncnice-trynerf-dartnode-emojinode-fetchnode-fetch-npmnode-gypnode-int64node-modules-regexpnode-notifiernode-releasesnormalize-pathnpmnoptnormalize-urlnpm-audit-reportnormalize-package-datanpm-cache-filenamenpm-bundlednpm-install-checksnpm-lifecyclenpm-logical-treenpm-normalize-package-binnpm-package-argnpm-packlistnpm-profilenpm-pick-manifestnpm-user-validatenpm-run-pathnpm-registry-fetchnpmlognumber-is-nannullthrowsnwsapiob1oauth-signobject-copyobject-assignobject-keysobject-inspectobject-visitobject.assignobject.fromentriesobject.entriesobject.getownpropertydescriptorsobject.pickon-finishedonceon-headersonetimeobject.valuesopenopeneroptionsoraoptionatoros-nameos-localeos-homediros-tmpdirosenvp-deferp-each-seriesp-filterp-finallyp-is-promisep-limitp-locatep-mapp-reducep-retryp-trypackage-jsonparent-moduleparallel-transformpacoteparse-github-repo-urlparse-jsonparse-node-versionparse5parseurlpascalcasepath-existspath-dirnamepath-keypath-is-absolutepath-is-insidepath-parsepath-typeperformance-nowpicomatchpinkie-promisepifypinkiepiratesplistpkg-confpnplugin-errorpkg-dirprelude-lsprepend-httpposix-character-classesprogressprocess-nextick-argspretty-formatpromise-eventspromise-inflightpromisepromise-retrypromptspromzardprop-typesproto-listprotoduckprrpseudomappslpumppumpifypunycodeqqrcode-terminalqsquick-lruquery-stringqwrcrange-parserreact-devtools-corereact-isreact-refreshread-cmd-shimreadread-package-jsonread-installedread-pkgread-package-treeread-pkg-upreadable-streamreaddir-scoped-modulesreaddirpredentredeyedrealpath-nativerechoirregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregex-notregexpu-coreregexp.prototype.flagsremove-trailing-separatorregistry-auth-tokenregexpprepeat-elementregjsgenregistry-urlregjsparserrepeat-stringrequestrepeatingrequest-promise-nativerequire-main-filenamerequire-directoryresolverequest-promise-coreresolve-cwdresolve-fromrestore-cursorresolve-urlretretryreusifyrsvprolluprun-asyncrimrafrun-parallelrun-queuerx-literx-lite-aggregatesrxjssafe-buffersafe-regexsanesaxsafer-bufferschedulersemantic-releasesemversemver-diffsemver-regexsendserve-staticserialize-errorset-blockingset-valuesetimmediatesetprototypeofshashebang-regexshebang-commandshell-quoteshelljsshellwordssignal-exitsignaleside-channelslashsimple-plistsisteransislice-ansislidesmart-buffersnapdragonsnapdragon-utilsnapdragon-nodesockssocks-proxy-agentsort-object-keyssorted-union-streamsort-package-jsonsorted-objectsource-mapsource-map-resolvesource-map-supportsource-map-urlsourcemap-codecspawn-error-forwarderspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit-on-firstsplit2sprintf-jssplit-stringsshpkssristack-utilsstatic-extendstacktrace-parserstatusesstealthy-requirestream-combiner2stream-buffersstream-eachstream-iteratestrict-uri-encodestream-shiftstring-widthstring-lengthstring.prototype.trimendstring_decoderstring.prototype.matchallstringify-packagestring.prototype.trimstartstrip-bomstrip-ansistrip-eofstrip-indentstrip-json-commentsstrip-final-newlinesudo-promptsymbol-observablesupports-hyperlinkssymbol-treetablesupports-colortemptartempfiletemp-dirtempyterm-sizetest-excludetext-tabletext-extensionsthroatthrough2throughtimed-outtime-stamptiny-relative-datetmptmplto-fast-propertiesto-object-pathto-regexto-regex-rangetoidentifiertr46traversetough-cookietrim-newlinestrim-off-newlinestsconfig-pathstslibtunnel-agenttweetnacltsutilstype-checkua-parser-jstype-festuglify-estypedarrayuid-numberuglify-jsumaskultronunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-property-aliases-ecmascriptunicode-match-property-value-ecmascriptunion-valueunique-filenameunique-slugunique-stringuniversal-user-agentuniversalifyunpipeunzip-responseupathunset-valueupdate-notifieruri-jsurl-joinurixuseurl-parse-laxutil-deprecateutil-extendutils-mergeutil-promisifyutil.promisifyv8-compile-cacheuuidvalidate-npm-package-licensevalidate-npm-package-namevaryvlqverrorwalkerw3c-hr-timewhatwg-encodingwcwidthwhatwg-fetchwebidl-conversionswhich-modulewhatwg-urlwhatwg-mimetypewhichwide-alignwidest-linewordwrapwindows-releasewrap-ansiword-wrapworker-farmwrappywritewswrite-file-atomicxcodexdg-basedirxml-name-validatorxmlbuilderxmldocxtendxmldomxpipeyallisty18nyamlyargsyargs-parser
1.0.0

3 years ago