react-native的渐变边框,用react-native-svg实现

实现代码如下:

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容