android - 在 Flutter 中剪切文本效果

标签 android ios flutter

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

这正是我的意思:

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

最佳答案

您必须使用 CustomPainterTextPainterBlendModesaveLayer:

result

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;
  }
}

关于android - 在 Flutter 中剪切文本效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52152018/

相关文章:

flutter - 禁用时如何更改下拉默认文本颜色?

flutter - 代码是正确的,但容器没有移动

android - Android Studio 0.2.1错误

android - 不同屏幕尺寸的 VideoView

ios - 访问扩展文件中一个文件中声明的变量时出现问题

flutter - 如何在 flutter 中将 child 定位在堆栈中?

android - 显示音频波形

java - 数据绑定(bind)和 Google 服务插件无法协同工作

ios - 如何删除字符串中的所有空格和\n\r?

ios - 跟踪用户浏览 iOS 应用的 UI 所花费的时间