Oliver Saintilien
Oliver Saintilien

Reputation: 305

How can I use my spritesheet of icons in react native?

How can I properly use sprite sheets in react-native? Or do people typically load icons separately and not use sprite sheets? Mind you this is not sprites for animation, just pure icons.

For example here is my sheet...

enter image description here

And here is the css for one icon...

.Sprite {
  background-image: url(./assets/images/spritesheet.png);
  background-repeat: no-repeat;
  display: inline-block;
}
.IconMenu30px {
  width: 30px;
  height: 30px;
  background-position: -53px -5px;
}

And I tried to translate this into React Native like this...

<Image source={require("../assets/images/spritesheet.png")} style={styles.menuIcon} />

const styles = StyleSheet.create({
 menuIcon: {
    width: 30,
    height: 30,
  },
})

But apparently there is no background position attribute in React Native.

Upvotes: 2

Views: 1610

Answers (2)

sinan
sinan

Reputation: 484

I was able to find a workaround to this issue.

i will explain what i did

  1. Firstly i created a SpriteIcon.tsx file as a container sprite icon image
import {
  Image,
  ImageSourcePropType,
  ImageStyle,
  StyleProp,
  StyleSheet,
  View,
  ViewStyle,
} from "react-native";

type PropType = {
  containerStyle: StyleProp<ViewStyle>;
  imageStyle: StyleProp<ImageStyle>;
  source: ImageSourcePropType;
};

const SpriteIcon = ({ containerStyle, imageStyle, source }: PropType) => {
  return (
    <View style={[styles.icon, containerStyle]}>
      <Image source={source} style={[styles.sprite, imageStyle]} />
    </View>
  );
};

const styles = StyleSheet.create({
  icon: {
    overflow: "hidden",
  },
  sprite: {
    position: "absolute",
  },
});

export default SpriteIcon;
  1. Secondly to get my icons dimensions i used spritecow website IMPORTANT: I selected 2x for mobile devices.

screenshot of value i got after selecting the icon i needed from spritecow website

import the SpriteIcon component wherever you need to use icons from sprite sheet and set the the style values properly like below

  1. set width and height of container from .sprite class's width and height.
  2. set width and height of image from .sprite class's background-size values.
  3. set left and top of image from .sprite class's background-position values.
<SpriteIcon
              containerStyle={{
                width: 40,
                height: 40,
              }}
              imageStyle={{
                width: 250,
                height: 335,
                left: -89,
                top: -65,
              }}
              source={require("../../../assets/images/icons_sprite.png")}
            />

This solution worked for me.

Upvotes: 0

Rose Kane Quinn
Rose Kane Quinn

Reputation: 45

Did you try

<ImageBackground />

This might help with your issue

Upvotes: 0

Related Questions