一、下载依赖?
npm install react-native-svg
二、使用步骤
1.创建 BrightnessIcon 组件来绘制太阳亮度图标。
代码如下(示例):
import React from 'react';
import { View, Dimensions } from 'react-native';
import Svg, { Path, Line, Text as SvgText } from 'react-native-svg';
import {combinations} from "expo-modules-autolinking/e2e/TestUtils";
const size = 75; // 固定组件大小为 240x240
//brightness 是亮度值
const MySunComponent = ({ brightness }) => {
let percent = Math.round(((brightness+1) / 32) * 100)>=100 ? 100 : Math.round(((brightness+1) / 32) * 100);
const radius = size / 2 - 20; // 半径,减去一些以避免边界问题
const centerX = size / 2; // 中心X
const centerY = size / 2; // 中心Y
const angle = percent >= 100 ? ((360 * percent) / 100)-0.001 : (360 * percent) / 100 ; // 根据亮度计算角度
const lineOffset = 3; // 圆形与线条之间的距离
const lineLength = 8; // 线条长度
const auto = $t("wifiSetting")
// 计算红色扇形路径
const redEndX = centerX + radius * Math.sin((Math.PI * angle) / 180);
const redEndY = centerY - radius * Math.cos((Math.PI * angle) / 180);
const redLargeArcFlag = angle > 180 ? 1 : 0;
const redPathData = `
M ${centerX} ${centerY}
L ${centerX} ${centerY - radius}
A ${radius} ${radius} 0 ${redLargeArcFlag} 1 ${redEndX} ${redEndY}
Z
`;
console.log(redPathData)
// 计算灰色扇形路径
const grayLargeArcFlag = angle <= 180 ? 1 : 0;
const grayPathData = `
M ${centerX} ${centerY}
L ${redEndX} ${redEndY}
A ${radius} ${radius} 0 ${grayLargeArcFlag} 1 ${centerX} ${centerY - radius}
Z
`;
// 计算线条的位置
const numLines = 12; // 可以根据需要调整线条数量
const lines = [];
for (let i = 0; i < numLines; i++) {
const lineAngle = (i * 360) / numLines;
const lineStartX = centerX + (radius + lineOffset) * Math.sin((Math.PI * lineAngle) / 180);
const lineStartY = centerY - (radius + lineOffset) * Math.cos((Math.PI * lineAngle) / 180);
const lineEndX = centerX + (radius + lineOffset + lineLength) * Math.sin((Math.PI * lineAngle) / 180);
const lineEndY = centerY - (radius + lineOffset + lineLength) * Math.cos((Math.PI * lineAngle) / 180);
lines.push(
<Line
key={i}
x1={lineStartX}
y1={lineStartY}
x2={lineEndX}
y2={lineEndY}
stroke={lineAngle <= angle ? "#62f906" : "#e5e5e5"}
strokeWidth="2"
/>
);
}
return (
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Svg height={size} width={size}>
<Path d={redPathData} fill="#62f906" />
<Path d={grayPathData} fill="#e5e5e5" />
{lines}
<SvgText
x={centerX}
y={centerY}
fill={brightness>32?"#444":"#333"}
fontSize={brightness>32?"11":"14"}
fontWeight="bold"
textAnchor="middle"
alignmentBaseline="middle"
>
{`${percent}%`}
</SvgText>
</Svg>
</View>
);
};
export default MySunComponent;
2.使用组件
代码如下(示例):
import BrightnessIcon from './BrightnessIcon'; // 确保路径正确)
export default function Brightness(props:any) {
const brightness = 75 ;//根据实际情况赋值
return (
<View style={styles.container}>
//将亮度值传入组件
<BrightnessIcon brightness={brightness} />
</View>
)
}
3.效果图
总结
小菜鸡玩代码