80 lines
1.8 KiB
Dart
80 lines
1.8 KiB
Dart
import 'dart:ui' as ui;
|
||
|
||
import 'package:flutter/material.dart';
|
||
import 'package:intl/intl.dart';
|
||
|
||
/// 防截屏水印(对应 Android WatermarkUtils)
|
||
class Watermark extends StatelessWidget {
|
||
final String text;
|
||
final int columns;
|
||
final int rows;
|
||
final double rotation;
|
||
|
||
const Watermark({
|
||
super.key,
|
||
required this.text,
|
||
this.columns = 4,
|
||
this.rows = 8,
|
||
this.rotation = -0.4,
|
||
});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return IgnorePointer(
|
||
ignoring: true,
|
||
child: CustomPaint(
|
||
painter: _WatermarkPainter(
|
||
text: '$text ${DateFormat('yyyy-MM-dd HH:mm').format(DateTime.now())}',
|
||
columns: columns,
|
||
rows: rows,
|
||
rotation: rotation,
|
||
),
|
||
child: const SizedBox.expand(),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
class _WatermarkPainter extends CustomPainter {
|
||
final String text;
|
||
final int columns;
|
||
final int rows;
|
||
final double rotation;
|
||
|
||
_WatermarkPainter({
|
||
required this.text,
|
||
required this.columns,
|
||
required this.rows,
|
||
required this.rotation,
|
||
});
|
||
|
||
@override
|
||
void paint(Canvas canvas, Size size) {
|
||
final textPainter = TextPainter(
|
||
text: TextSpan(
|
||
text: text,
|
||
style: TextStyle(
|
||
color: Colors.black.withValues(alpha: 0.06),
|
||
fontSize: 14,
|
||
),
|
||
),
|
||
textDirection: ui.TextDirection.ltr,
|
||
)..layout();
|
||
|
||
final dx = size.width / columns;
|
||
final dy = size.height / rows;
|
||
|
||
for (int i = 0; i <= columns; i++) {
|
||
for (int j = 0; j <= rows; j++) {
|
||
canvas.save();
|
||
canvas.translate(i * dx, j * dy);
|
||
canvas.rotate(rotation);
|
||
textPainter.paint(canvas, const Offset(0, 0));
|
||
canvas.restore();
|
||
}
|
||
}
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(_WatermarkPainter old) => old.text != text;
|
||
} |