Reputation: 305
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...
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
Reputation: 484
I was able to find a workaround to this issue.
i will explain what i did
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;
import the SpriteIcon component wherever you need to use icons from sprite sheet and set the the style values properly like below
<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
Reputation: 45
Did you try
<ImageBackground />
This might help with your issue
Upvotes: 0