[英]What is the difference between CustomPainter and CustomClipper?
I am currently reading about Flutter and came to know that shapes can be created using CustomPainter and CustomClipper.我目前正在阅读有关 Flutter 的文章,并了解到可以使用 CustomPainter 和 CustomClipper 创建形状。 Shapes like Rectangle, oval etc.. can be created using both so what is the difference between them and when should either of them be used?
可以使用两者创建矩形、椭圆形等形状,那么它们之间有什么区别以及何时应该使用它们中的任何一个?
A clipper is used to restrict the rendering to a particular area.裁剪器用于将渲染限制在特定区域。 The rendering engine will only "paint" the pixels inside of the defined area.
渲染引擎只会“绘制”定义区域内的像素。 A
CustomClipper
will be mostly used with a ClipPath
widget. CustomClipper
将主要与ClipPath
小部件一起使用。
class MyCustomClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
// Implement your custom clipper path
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
ClipPath(
clipper: MyCustomClipper(),
child: Container(
width: 200,
height: 200,
color: Colors.blue,
),
);
This interface is used alongside the CustomPaint
which provides a canvas on which you can draw images and shapes.该界面与
CustomPaint
一起使用,它提供了一个画布,您可以在其上绘制图像和形状。
class MyCustomPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// Implement your custom painter
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}
CustomPaint(
painter: MyCustomPainter(),
);
To resume: CustomClipper
is restricting the painting area, while CustomPainter
gives you a canvas to paint freely.继续:
CustomClipper
限制了绘画区域,而CustomPainter
为您提供了一个可以自由绘画的画布。
While you might be able to acomplish similar results with both depending on your use case it might be easier to use CustomClipper
or CustomPainter
.虽然您可能能够根据您的用例使用两者完成类似的结果,但使用
CustomClipper
或CustomPainter
可能更容易。
For example if you only want to have some custom shape for a Container
or an Image
it will be much easier to do it with a CustomClipper
compared to a CustomPainter
as you will only need to define the path in which your widget will be rendered and you will still have access to all the properties of your widget.例如,如果您只想为
Container
或Image
设置一些自定义形状,与CustomPainter
相比,使用CustomClipper
会更容易完成,因为您只需要定义小部件将在其中呈现的路径,并且您仍然可以访问您的小部件的所有属性。
Now let's take another example, if you want to create your own CircularProgressIndicator
widget.现在让我们再举一个例子,如果你想创建你自己的
CircularProgressIndicator
小部件。 In this case you might have a hard time by using the CustomClipper
while thanks to CustomPainter
you will be able to draw your widget much more freely and it will also be easier to animate.在这种情况下,您可能很难使用
CustomClipper
而感谢CustomPainter
您将能够更自由地绘制您的小部件,并且也更容易制作动画。 (If you take a look at how the ProgressIndicator
are coded you will see that they are using CustomPainter
) (如果您查看
ProgressIndicator
的编码方式,您会发现它们使用的是CustomPainter
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.