Search code examples
react-nativereact-native-stylesheet

How to draw a circle ring


I would like to draw a circle ring in react-native project. I would like the circle ring component be customised in its size when using it. Here is what I tried:

import React from 'react';
import {View, StyleSheet, TouchableOpacity} from 'react-native';

const Ring = ({size}) => {
  return (
      <View
        style={[styles.circle, {width: size, height: size}]}
      />
  );
};

const styles = StyleSheet.create({
  circle: {
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 15,
    borderColor: 'blue',
  },
});

export default Ring;

When I use my Ring component, like this:

const MyScreen = () => {
  return (
    <TouchableOpacity>
      <View style={styles.container}>
        <Ring size={6} />
        <Text>XYZ</Text>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    paddingVertical: 17,
    paddingHorizontal: 36,
  },
});
export default MyScreen;

it however shows a filled circle instead of a ring shape. How can I have a circle ring?


Solution

  • The problem you have is having a higher value for the borderWidth. You can change the styles like below

      circle: {
        width: 100,
        height: 100,
        borderRadius: 50,
        borderWidth: 2,
        borderColor: 'blue',
      },
    

    Or have a dyanamic value for borderWidth and others like below

    const Ring = ({ size }) => {
      return (
        <View
          style={[
            styles.circle,
            {
              width: size,
              height: size,
              borderRadius: size / 2,
              borderWidth: (size * 5) / 100,
            },
          ]}
        />
      );
    };
    

    Calculating the boderRadius would help when the size is over 50 and will always produce a circle.