React Native rounded image with a border
I want to create a rounded image with a border. If I add borderColor: 'green', borderWidth:1
, border is visible only in top left part of the rounded image.
<TouchableHighlight
style={[styles.profileImgContainer, { borderColor: 'green', borderWidth:1 }]}
>
<Image source={{ uri:"https://www.t-nation.com/system/publishing/articles/10005529/original/6-Reasons-You-Should-Never-Open-a-Gym.png" }} style={styles.profileImg} />
</TouchableHighlight>
export default styles = StyleSheet.create({
profileImgContainer: {
marginLeft: 8,
height: 80,
width: 80,
borderRadius: 40,
},
profileImg: {
height: 80,
width: 80,
borderRadius: 40,
},
});
overflow: 'hidden'
for images container solves this issue.
Use the following styling, it's work for me.
image: {
width: 150,
height: 150,
borderRadius: 150 / 2,
overflow: "hidden",
borderWidth: 3,
borderColor: "red"
}
Worth to mention for Android...
I had to specifically set resizeMode="cover"
for the borderRadius to take effect.
<Image
style={styles.image}
source={source}
resizeMode={"cover"} // <- needs to be "cover" for borderRadius to take effect on Android
/>
const styles = StyleSheet.create({
image: {
width: 150,
height: 150,
borderColor: 'red,
borderWidth: 2,
borderRadius: 75
},
});
Border width adds up to the size of the component that you added to. This makes your image bigger than the size of your container component. To solve this issue you can add the border width to the component sizes.
Example
const styles = StyleSheet.create({
profileImgContainer: {
marginLeft: 8,
height: 82,
width: 82,
borderRadius: 40,
borderWidth: 1
},
profileImg: {
height: 80,
width: 80,
borderRadius: 40,
},
});
The answers given here, are nice, but, from my experience, it's better to use percentages of your available screen height, as the width and height dimensions of image. This will help a lot with responsiveness. Do it like this
import RN from 'react-native';
const SCREEN_HEIGHT = RN.Dimensions.get('window').height;
Then apply the following as the dimensions styling, to get a nice, responsive rounded image.
style={[
//... your other previous styles
{
resizeMode: 'cover',
width: SCREEN_HEIGHT * 0.15,
height: SCREEN_HEIGHT * 0.15,
borderRadius: (SCREEN_HEIGHT * 0.15)/2,
}
]}
The (*0.15 i.e 15% of screen height) is just my choice of sample dimensions, you can use higher or lower, depending on how big you want your image to be.