首页 > 解决方案 > 如何画一个圆环

问题描述

我想在 react-native 项目中画一个圆环。我希望圆环组件在使用时可以自定义其大小。这是我尝试过的:

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;

当我使用我的Ring组件时,如下所示:

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;

然而,它显示了一个实心圆圈而不是环形。我怎样才能有一个圆环?

标签: react-nativereact-native-stylesheet

解决方案


您遇到的问题是borderWidth 的值更高。您可以更改如下样式

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

或者为borderWidth和其他类似下面的动态值

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

当大小超过 50 时,计算 boderRadius 会有所帮助,并且总是会产生一个圆。


推荐阅读