我正在尝试学习CustomPainter
。我已经成功创建了两个矩形,并试图理解BlendMode
。
正如文档中所说的,当设置paintObj.blendMode = BlendMode.src
时,它应该
丢弃目标图像,仅绘制源图像。
但是这里目标和源都画在彼此的顶部,而不是清除目标。
这是完整代码:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SizedBox.expand(
child: CustomPaint(
painter: MyPainter(),
),
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paintObj = Paint();
paintObj.color = Colors.red;
canvas.drawRect(
Rect.fromCircle(
center: size.center(Offset.zero),
radius: 40.0,
),
paintObj,
);
paintObj.blendMode = BlendMode.src;
paintObj.color = Colors.green;
canvas.drawRect(
Rect.fromCenter(
center: size.center(Offset.zero),
height: 160,
width: 40,
),
paintObj,
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
结果:我不知道为什么仍然绘制红色矩形(目标)
我在这里想念什么?
似乎表现出预期。
Paint
的blendMode
的文档:
/// A blend mode to apply when a shape is drawn or a layer is composited.
///
/// The source colors are from the shape being drawn (e.g. from
/// [Canvas.drawPath]) or layer being composited (the graphics that were drawn
/// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying
/// the [colorFilter], if any.
///
/// The destination colors are from the background onto which the shape or
/// layer is being composited.
///
/// Defaults to [BlendMode.srcOver].
BlendMode.src
的文档:
/// Drop the destination image, only paint the source image.
///
/// Conceptually, the destination is first cleared, then the source image is
/// painted.
我相信目的地被认为是绿色矩形(大小完全相同)下方的矩形,而不是整个画布。这是有道理的,因为与清除整个画布相比,CustomPainer
具有更大的灵活性。您应该能够使用半透明的颜色进行测试。如果我的假设正确,则半透明的绿色矩形应具有统一的颜色,因为红色矩形将首先从其下方清除。
void paint(Canvas canvas, Size size) {
final paintObj = Paint();
canvas.saveLayer(
Rect.fromCircle(center: Offset(size.width, size.height), radius: 100),
paintObj);
paintObj.color = Colors.red;
canvas.drawRect(
Rect.fromCircle(
center: size.center(Offset.zero),
radius: 40.0,
),
paintObj,
);
paintObj.blendMode = BlendMode.src;
paintObj.color = Colors.green;
canvas.drawRect(
Rect.fromCenter(
center: size.center(Offset.zero),
height: 160,
width: 40,
),
paintObj,
);
canvas.restore();
}