Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active September 25, 2021 17:18
Show Gist options
  • Save bitsmanent/16b5bd4c8c1f70846510ffbcfd53ab16 to your computer and use it in GitHub Desktop.
Save bitsmanent/16b5bd4c8c1f70846510ffbcfd53ab16 to your computer and use it in GitHub Desktop.
Simple sprite sheets for React Native
import React from "react";
import {ImageBackground} from "react-native";
export function Sprite(props) {
const [w, h] = [props.geometry.width, props.geometry.height];
const r = Math.min(w / (props.width / props.cols), h / (props.height / props.rows));
return (
<ImageBackground
source={props.source}
style={{
width: w,
height: h,
overflow: "hidden"
}}
imageStyle={{
width: props.width * r,
height: props.height * r,
left: props.geometry.x,
top: props.geometry.y
}}
/>)
}
@bitsmanent
Copy link
Author

bitsmanent commented Sep 16, 2021

Usage:

import {Sprite} from "./react-native-sprite.js";

<Sprite source={require("path/of/sprite.png")}
  width={100} height={255}
  rows={1} cols={20}
  geometry={{
    width: 48,
    height: 48,
    x: 0,
    y: -48 * 3
  }} />

Where:

  • source: full path of the sprite also remote (see ImageSource)
  • width: width of the sprite image
  • height: height of the sprite image
  • rows: number of rows in the sprite
  • cols: number of columns in the sprite
  • geometry: width, height and offset (y,x) of the sprite portion to show (the actual icon)

If icons have all the same height you can use the -h*n formula to select the nth icon in the sprite (as the above example).

Enjoy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment