custompaint 介绍
flutter custompaint 提供了一个 canvas,可以在绘制阶段在上面进行绘制内容。
需要绘制时,custompaint 首先要求它的 painter 在当前画布上绘画,然后它绘画它的 child,在绘画完它的 child 之后,要求他的 foregroundpainter 绘画。
需要在从原点开始并包含给定大小的区域的矩形内作画。 (如果在这些边界之外绘画,则分配的内存可能不足以光栅化绘画命令,并且结果行为未定义。)要保证在这些边界内绘画,请考虑使用 cliprect。
使用 custompaint
const custompaint({
super.key,
this.painter,
this.foregroundpainter,
this.size = size.zero,
this.iscomplex = false,
this.willchange = false,
super.child,
})
最重要就是这个 painter,painter 需要自定义。
class mypainter extends custompainter {
@override
void paint(canvas canvas, size size) {
var paint = paint()
..color = colors.red
..style = paintingstyle.stroke
..strokewidth = 1.0;
canvas.drawline(
offset(0, 10),
offset(
100,
10,
),
paint);
}
@override
bool shouldrepaint(covariant custompainter olddelegate) {
return false;
}
}
需要重写两个方法,在 paint 方法中进行绘制。如果绘制不受外界影响,shouldrepaint 返回 false 就好。
custompaint(painter: mypainter(),);
把 mypainter 赋值给参数 painter 就好了。
size 的大小。
如果 custompaint 的约束可以为 0 的话,那么 size 的值 size(0,0),就是说,size 的值总是 constrains 的最小 width,最小 height。有两种办法可以改变 size。
- 可以给 custompaint 加上约束,比如加一个 sizedbox
sizedbox(
height: 20,
width: 20,
child: custompaint(
painter: mypainter(),
))
- 可以直接指定 size 参数。
sizedbox(
height: 20,
width: 20,
child: custompaint(
size:size(30,30),
painter: mypainter(),
))
size 参数可以在 constrains 的范围内起到作用。在本例中,约束为 20, size 为 30,最后传给 paint 方法的 size 为 20。 tight 约束下 size 参数无效,只有 在loose 约束下 ,size 参数才能起到作用。
iscomplex
是否提示应该缓存该层的绘画。如果 为false,则合成器将自己来决定这一层是否应该缓存。
willchange
是否应该告知缓存层这幅画在下一帧中可能会发生变化。如果 iscomplex 为 true,才需要考虑这个参数。
foregroundpainter
默认绘制的层是在 child 之下,foregroundpainter 在 child 之上。
动画
custompainter 有一个 可选的参数 listenable? repaint ,是用来做动画的。
举个例子。
class mypainter extends custompainter {
mypainter(animation<double> animation) :_animation=animation, super(repaint: animation);
final animation<double> _animation;
@override
void paint(canvas canvas, size size) {
var paint = paint()
..color = colors.red
..style = paintingstyle.stroke
..strokewidth = 1.0;
canvas.drawline(
offset(0, 10),
offset(
100*_animation.value,
10,
),
paint);
}
@override
bool shouldrepaint(covariant custompainter olddelegate) {
return false;
}
}
class mystatefulwidget extends statefulwidget {
const mystatefulwidget({super.key});
@override
state<mystatefulwidget> createstate() => _mystatefulwidgetstate();
}
class _mystatefulwidgetstate extends state<mystatefulwidget> with singletickerproviderstatemixin{
late animationcontroller controller=
animationcontroller(duration: duration(seconds: 2),vsync: this)..repeat();
@override
widget build(buildcontext context) {
return sizedbox(
height: 20,
width: 20,
child: custompaint(
painter: mypainter(controller.view),
));
}
}
会看到一条红色的直线由短变长。
以上就是flutter custompaint绘制widget使用示例的详细内容,更多关于flutter custompaint绘制widget的资料请关注代码网其它相关文章!
发表评论