效果
封装
写一个将水印内容渲染到整个页面的组件,再全局引入。
Watermark.tsx
import React, {useEffect, useState} from 'react';
import {View, Text, StyleSheet, Dimensions} from 'react-native';
const Watermark: React.FC = () => {
const [screenWidth, setScreenWidth] = useState(
Dimensions.get('window').width,
);
const [screenHeight, setScreenHeight] = useState(
Dimensions.get('window').height,
);
useEffect(() => {
// 获取屏幕宽度和高度
const updateDimensions = () => {
setScreenWidth(Dimensions.get('window').width);
setScreenHeight(Dimensions.get('window').height);
};
const subscription = Dimensions.addEventListener('change', updateDimensions);
return () => {
subscription?.remove();
};
}, []);
// 水印行数和列数
const rows = Math.ceil(screenHeight / 60); // 每行高度为 60,可根据需要调整
const cols = Math.ceil(screenWidth / 60); // 每列宽度为 60,可根据需要调整
// 生成水印数组
const watermarks = [];
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
watermarks.push(
<Text key={`${i}-${j}`} style={styles.watermarkText}>
水印内容123456
</Text>,
);
}
}
return <View style={styles.watermarkContainer}>{watermarks}</View>;
};
const styles = StyleSheet.create({
watermarkContainer: {
position: 'absolute',
top: -200,
left: -200,
right: -200,
bottom: 0,
opacity: 0.5,
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
flexWrap: 'wrap',
transform: [{rotate: '-20deg'}],
zIndex: 999,
pointerEvents: 'none', // 让点击事件透传
},
watermarkText: {
fontSize: 12,
marginTop: 24,
marginBottom: 24,
marginLeft: 20,
marginRight: 20,
color: '#CFD8E1', // 调整颜色和透明度
},
});
export default Watermark;
使用
import Watermark from '@/components/Watermark';
<Watermark />
举例
在 App.tsx 文件中使用:
<Watermark /> 只能放在 <Route /> 之后,将 <Watermark /> 放在 <Route /> 之前,那么根据渲染顺序, <Watermark /> 会被首先渲染,然后才是 <Route /> ,所以 <Watermark /> 在 <Route /> 前将导致不显示水印内容。
// App.tsx
import * as React from 'react';
import Watermark from '@/components/Watermark';
import Route from '@/router';
function App(): React.JSX.Element {
return (
<>
<Route />
<Watermark />
</>
);
}
export default App;