使用 Custom Painter 在 Flutter 中掩盖路径和绘画
Posted
技术标签:
【中文标题】使用 Custom Painter 在 Flutter 中掩盖路径和绘画【英文标题】:Masking a path and paint in Flutter using a Custom Painter 【发布时间】:2020-11-19 03:53:24 【问题描述】:我想根据需要为线条着色,通过使用drawPath
来掩盖drawPaint
。但我发现正确结果后面有黑色背景like this。当我使用BlendMode.src
时检查src(线路),我发现我的线路like this也有黑色背景,有什么办法避免它?
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
void main() => runApp(StartPage());
class StartPage extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
home: TestPage(),
);
class TestPage extends StatelessWidget
@override
Widget build(BuildContext context)
return Scaffold(
body: CustomPaint(
painter: PaintDemo(),
size: Size.infinite,
),
);
class PaintDemo extends CustomPainter
@override
void paint(Canvas canvas, Size size)
var startPoint = Offset(0, 0);
var controlPoint1 = Offset(size.width / 2, 0);
var controlPoint2 = Offset(size.width / 2, size.height);
var endPoint = Offset(size.width, size.height);
var path = Path()
..moveTo(startPoint.dx, startPoint.dy)
..cubicTo(controlPoint1.dx, controlPoint1.dy, controlPoint2.dx,
controlPoint2.dy, endPoint.dx, endPoint.dy);
canvas.save();
canvas.drawPaint(
Paint()
..shader = ui.Gradient.linear(
Offset(size.width / 2, 0),
Offset(size.width / 2, size.height),
[
Color(0xFF32D74B),
Color(0xFFFF453A),
],
),
);
canvas.restore();
canvas.saveLayer(
Rect.fromLTRB(0, 0, size.width, size.height),
Paint()..blendMode = BlendMode.dstIn,
);
canvas.drawPath(
path,
Paint()
..isAntiAlias = true
..color = Colors.orange
..style = PaintingStyle.stroke
..strokeWidth = 3);
canvas.restore();
@override
bool shouldRepaint(CustomPainter oldDelegate)
return true;
【问题讨论】:
【参考方案1】:我在没有更改 dartpad 中的单个字符的情况下测试了您的代码,并且没有看到黑色背景。请看截图。
【讨论】:
以上是关于使用 Custom Painter 在 Flutter 中掩盖路径和绘画的主要内容,如果未能解决你的问题,请参考以下文章