实现代码如下:
import BlurView from '@sbaiahmed1/react-native-blur';
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import Svg, { Rect, Defs, LinearGradient, Stop } from 'react-native-svg';
export const AutoGlassBorder = ({ style, children, borderRadius = 20, strokeWidth = 2 }) => {
const [layout, setLayout] = useState({ width: 0, height: 0 });
const onLayout = (event) => {
const { width, height } = event.nativeEvent.layout;
setLayout({ width, height });
};
return (
<View onLayout={onLayout} style={{ overflow: 'hidden', ...style }}>
<BlurView
style={{
borderRadius: borderRadius,
padding: strokeWidth,
}}
blurType="light"
blurAmount={20}>
{children}
</BlurView>
{layout.width > 0 &&
<Svg
style={{ ...StyleSheet.absoluteFill }}
viewBox={`0 0 ${layout.width} ${layout.height}`}>
<Defs>
<LinearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<Stop offset="0" stopColor="rgba(255, 255, 255, 1)" stopOpacity="0.5" />
<Stop offset="0.5" stopColor="rgba(255, 255, 255, 0)" stopOpacity="0.1" />
<Stop offset="1" stopColor="rgba(255, 255, 255, 1)" stopOpacity="0.5" />
</LinearGradient>
</Defs>
<Rect
x={strokeWidth / 2}
y={strokeWidth / 2}
width={layout.width - strokeWidth}
height={layout.height - strokeWidth}
rx={borderRadius - strokeWidth / 2}
ry={borderRadius - strokeWidth / 2}
stroke="url(#grad)"
strokeWidth={strokeWidth}
fill="none"
/>
</Svg>
}
</View >
);
};
使用方法如下:
<AutoGlassBorder
style={{
position: 'absolute',
top: 100,
left: 0,
right: 50,
}}
borderRadius={60}
strokeWidth={1}
children={<View style={{ }}>
<UIText style={{ height: 200, textAlign: 'center', }}>renderGlassView</UIText>
</View>} />
效果如下

image.png