flutter如何给图片添加水印
在 Flutter 中如何给图片添加文字或图片水印?有没有简单的实现方法或推荐的插件?
        
          2 回复
        
      
      
        在Flutter中,使用Stack和Positioned组件叠加图片和水印文本或图片,通过调整位置和透明度实现水印效果。
更多关于flutter如何给图片添加水印的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中给图片添加水印,主要有以下几种方法:
1. 使用Stack组件叠加水印(简单静态水印)
Stack(
  children: [
    Image.asset('assets/original_image.jpg'),
    Positioned(
      bottom: 10,
      right: 10,
      child: Text(
        '水印文字',
        style: TextStyle(
          color: Colors.white.withOpacity(0.7),
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
    ),
  ],
)
2. 使用CustomPaint绘制水印
CustomPaint(
  painter: WatermarkPainter(),
  child: Image.asset('assets/original_image.jpg'),
)
class WatermarkPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final textStyle = TextStyle(
      color: Colors.white.withOpacity(0.5),
      fontSize: 20,
    );
    final textSpan = TextSpan(text: '我的水印', style: textStyle);
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();
    
    // 在右下角绘制水印
    final offset = Offset(
      size.width - textPainter.width - 10,
      size.height - textPainter.height - 10
    );
    textPainter.paint(canvas, offset);
  }
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
3. 使用image_memory_saver库(推荐用于保存带水印的图片)
首先添加依赖:
dependencies:
  image_memory_saver: ^1.0.0
import 'package:image_memory_saver/image_memory_saver.dart';
// 添加水印并保存
Future<void> addWatermarkAndSave() async {
  final ByteData imageData = await rootBundle.load('assets/original_image.jpg');
  final Uint8List imageBytes = imageData.buffer.asUint8List();
  
  final watermarkedBytes = await ImageMemorySaver.addTextWatermark(
    imageBytes,
    '水印文字',
    position: WatermarkPosition.bottomRight,
    textStyle: TextStyle(
      color: Colors.white.withOpacity(0.7),
      fontSize: 24,
    ),
  );
  
  // 保存到相册或文件
  await ImageMemorySaver.saveImage(watermarkedBytes);
}
4. 使用flutter_watermark插件
dependencies:
  flutter_watermark: ^1.0.0
import 'package:flutter_watermark/flutter_watermark.dart';
Watermark(
  text: '水印文字',
  textColor: Colors.white.withOpacity(0.6),
  fontSize: 18,
  child: Image.asset('assets/original_image.jpg'),
)
选择建议:
- 简单显示:使用Stack或CustomPaint
- 需要保存带水印的图片:使用image_memory_saver
- 全屏水印:使用CustomPaint绘制重复水印图案
这些方法都能有效实现图片水印功能,根据具体需求选择合适的方式即可。
 
        
       
             
             
            

