Reputation: 3
I just want to know how to display a part of an image in react-native
class InstaClone extends Component {
render() {
return(
<View style={{ flex:1, width:100 + "%", height:100 + "%" }}>
<View style={styles.TopNavStyle}>
<Text style={styles.TopNavTextStyle}>
Instagram
</Text>
</View>
<View style = {styles.userBar}>
<View style = {{ flexDirection:"row" , alignItems:"center" }}>
<Image style = {styles.userPic}
source = {require('../assets/images/photoUser.jpg')}/>
<Text style = {{marginLeft : 10}}>
Mohcouch
</Text>
</View>
<View>
<View style={styles.imageContainer}>
<ImageBackground
source={require('../assets/images/icons.jpg')}
style={styles.image}
></ImageBackground>
</View>
</View>
</View>
<Image
style={{ width:"100%", height:400 }}
source={require('../assets/images/baby.jpg')}
/>
</View>
)
}
}
} , image: {
height: 500,
width: 500,
resizeMode:"cover",
translateX:-80,
translateY: -135,
},
imageContainer: {
height: 40,
backgroundColor:'transparent',
width: 40,
},
})
export default InstaClone
Result :
Upvotes: 0
Views: 766
Reputation: 15713
React Native doesn's support a property background-position
. It is better to separate the icons in different image files.
But there is a tricky workaround that you can use with your sprite image:
First, you need to round the image pixels in layout size (dp):
const width = PixelRatio.roundToNearestPixel(280);
const height = PixelRatio.roundToNearestPixel(280);
Note: 280 is the size of the image from your post
Then, we need to calculate the same proportion for the size of the icon:
const iconWidth = PixelRatio.roundToNearestPixel(30);
const iconHeight = PixelRatio.roundToNearestPixel(30);
Note: 30 is a random size for our icon, it can be any size.
Now, for the loading of the image, we will use the ImageBackground
component from react-native. For imageStyle
we will pass the positioning properties of the image:
imageStyle={{
resizeMode: 'cover',
width: width, height: height,
top: -15,
left: -15
}}
Your component should look like this:
<ImageBackground
source={{ uri: image_url }}
style={{ width: iconWidth, height: iconHeight, overflow: 'hidden' }}
imageStyle={{
resizeMode: 'cover',
width: width, height: height,
top: -15,
left: -15
}}
/>
Here is a working demo.
Upvotes: 2