android - 在 Flutter 中剪切文本效果

如何将文本剪切到一个盒子容器中,让其下方的内容可见?

这正是我的意思:

如您所见,图片显示在文字下方。我怎么能这样做?

最佳答案

您必须使用 CustomPainterTextPainterBlendModesaveLayer:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Playground',
      home: TestPage(),
    );
  }
}

class TestPage extends StatelessWidget {
  const TestPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            image: AssetImage('assets/3g.jpg'), fit: BoxFit.cover),
      ),
      child: Center(
        child: CustomPaint(
          painter: CutOutTextPainter(text: 'YOUR NAME'),
        ),
      ),
    );
  }
}

class CutOutTextPainter extends CustomPainter {
  CutOutTextPainter({required this.text}) {
    _textPainter = TextPainter(
      text: TextSpan(
        text: text,
        style: const TextStyle(
          fontSize: 40.0,
          fontWeight: FontWeight.w600,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    _textPainter.layout();
  }

  final String text;
  late final TextPainter _textPainter;

  @override
  void paint(Canvas canvas, Size size) {
    // Draw the text in the middle of the canvas
    final textOffset =
        size.center(Offset.zero) - _textPainter.size.center(Offset.zero);
    final textRect = textOffset & _textPainter.size;

    // The box surrounding the text should be 10 pixels larger, with 4 pixels corner radius
    final boxRect = RRect.fromRectAndRadius(
        textRect.inflate(10.0), const Radius.circular(4.0));
    final boxPaint = Paint()
      ..color = Colors.white
      ..blendMode = BlendMode.srcOut;

    canvas.saveLayer(boxRect.outerRect, Paint());

    _textPainter.paint(canvas, textOffset);
    canvas.drawRRect(boxRect, boxPaint);

    canvas.restore();
  }

  @override
  bool shouldRepaint(CutOutTextPainter oldDelegate) {
    return text != oldDelegate.text;
  }
}

https://stackoverflow.com/questions/52152018/

相关文章:

dart - 如何在没有 Scaffold.drawer 的情况下使用 Drawer?

flutter - Sizedbox 与填充列和行中的距离

firebase - Flutter - firebase_auth updateProfile 方

flutter - 加载数据时制作骨架屏幕的最简单方法

dart - Flutter 小部件测试 : StreamBuilder snapshot has

flutter - 内置值对象的 setter 是什么

dart - 在初始化程序中只能访问静态成员。 Dart2.0

dart - 具有水平列表和网格的 Flutter 可滚动主体作为子项

dart - flutter 错误 : Could not find the correct Sco

dart - 在 Flutter 中从文件中读取二维码