我只想知道如何在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,
},
})
导出默认的 InstaClone
结果:
最佳答案
React Native 不支持属性 background-position
。最好将不同图像文件中的图标分开。
但是有一个棘手的解决方法可以用于您的 sprite 图像:
首先,您需要在布局尺寸 (dp) 中对图像像素进行舍入:
const width = PixelRatio.roundToNearestPixel(280);
const height = PixelRatio.roundToNearestPixel(280);
注意:280 是您帖子中图片的大小
然后,我们需要计算图标大小的相同比例:
const iconWidth = PixelRatio.roundToNearestPixel(30);
const iconHeight = PixelRatio.roundToNearestPixel(30);
注意:30 是我们图标的随机大小,它可以是任何大小。
现在,为了加载图像,我们将使用来自 react-native 的 ImageBackground
组件。 .对于 imageStyle
,我们将传递图像的定位属性:
imageStyle={{
resizeMode: 'cover',
width: width, height: height,
top: -15,
left: -15
}}
你的组件应该是这样的:
<ImageBackground
source={{ uri: image_url }}
style={{ width: iconWidth, height: iconHeight, overflow: 'hidden' }}
imageStyle={{
resizeMode: 'cover',
width: width, height: height,
top: -15,
left: -15
}}
/>
这是一个有效的 demo .
关于javascript - 裁剪图标图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55808942/