用颤抖的画布在形状上切孔

时间:2019-07-07 16:07:55

标签: flutter dart

如何用颤动的画布在形状上“切孔”? 我有一组相当复杂的形状,看起来像真实世界的对象。该物体上有一个像圆角矩形的孔。

我真的很想从形状中减去RRect,但是我找不到有关如何执行此操作的任何信息。 canvas.clipRRect(myRRect)只会删除myRRect未涵盖的所有内容。我要相反。即在当前的一个或多个画布形状中创建一个myRRect形状孔。

3 个答案:

答案 0 :(得分:14)

您可以将Path.combinedifference操作一起使用来创建孔。

自定义画家:

class HolePainter extends CustomPainter {

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.blue;
    canvas.drawPath(
        Path.combine(
          PathOperation.difference,
          Path()..addRRect(RRect.fromLTRBR(100, 100, 300, 300, Radius.circular(10))),
          Path()
            ..addOval(Rect.fromCircle(center: Offset(200, 200), radius: 50))
            ..close(),
        ),
        paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return null;
  }

}

用法:

class EditAvatar extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('Hole in rounded rectangle'),
      ),
      body: CustomPaint(
        painter: HolePainter(),
        child: Container(),
      ),

  }

}

结果:

enter image description here

当然,如果您希望孔是圆形的,则只需减去RRect而不是Circle

答案 1 :(得分:1)

您可以在Custom Painter中尝试使用不同的BlendMode,以下是您可以参考的示例之一:

class MyPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // below one is big circle and instead of this circle you can draw your shape here.
    canvas.drawCircle(Offset(200, 200), 100, Paint()
      ..color = Colors.orange[200]
      ..style = PaintingStyle.fill);

    // below the circle which you want to create a cropping part.
    RRect rRect = RRect.fromRectAndRadius(Rect.fromCenter(center: Offset(200, 200), width: 75, height: 75), Radius.circular(8));
    canvas.drawRRect(rRect, Paint()
      ..color = Colors.orange[200]
      ..style = PaintingStyle.fill
      ..blendMode = BlendMode.dstOut);

    canvas.save();
    canvas.restore();
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

在这里,我使用了BlendMode.dstOut,它将用于显示目标源,但仅用于显示两个源不重叠的位置。

答案 2 :(得分:0)

一种解决方案是使用PathFillType.evenOdd

// circle with empty RRect inside
final Path path = Path();
path.fillType = PathFillType.evenOdd;
path.addOval(Rect.fromCircle(center: center, radius: radius));
path.addRRect(RRect.fromRectAndRadius(
    Rect.fromCircle(center: center, radius: radius / 2),
    Radius.circular(radius / 10)));
canvas.drawPath(path, paint);

enter image description here