如何将矩阵滤镜应用于画布?

时间:2019-07-10 15:47:47

标签: canvas flutter dart paint colorfilter

我正在使用Flutter框架和Dart开发图像编辑器,但无法将矩阵滤镜应用于画布。

我正在尝试使用“ Paint”类和“ canvas.drawPaint(paint)”函数将矩阵滤镜应用于画布,但是我得到了黑色画布。

Original image

Expected (Variant 2 in code)

I get

class EditorPainter extends CustomPainter {

  final ui.Image image;
  final double zoom;
  final Offset offset;

  EditorPainter({
    @required this.image,
    @required this.zoom,
    @required this.offset,
    this.elements
  });

  @override
  void paint(Canvas canvas, Size size) {
    Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
    Size targetSize = imageSize * zoom;

    // Variant 1 - not working (draws black canvas)

    paintImage(
      canvas: canvas,
      rect: offset & targetSize,
      image: image,
      fit: BoxFit.fill
    );


    // Paint with "sepia" filter
    final Paint paint = Paint()
      ..colorFilter = ColorFilter.matrix([
        0.393, 0.768, 0.189, 0.0, 0.0,
        0.349, 0.686, 0.168, 0.0, 0.0,
        0.272, 0.534, 0.131, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.0, 0.0,
      ]);

    canvas.drawPaint(paint);

    // Variant 2 - working 
    // Image with "sepia" filter
    paintImage(
      canvas: canvas,
      rect: offset & targetSize,
      image: image,
      fit: BoxFit.fill,
      colorFilter: ColorFilter.matrix([
        0.393, 0.768, 0.189, 0.0, 0.0,
        0.349, 0.686, 0.168, 0.0, 0.0,
        0.272, 0.534, 0.131, 0.0, 0.0,
        0.0, 0.0, 0.0, 1.0, 0.0,
      ])
    );
  }
}

我希望得到一个带有过滤图像的画布,但是我得到一个黑色画布。 我试图将BlendMode分配给Paint,但没有帮助。

1 个答案:

答案 0 :(得分:1)

drawPaint用给定的Paint填充画布。在您的情况下,它会用黑色填充。

您应该修改第一个示例:

final matrix = ColorFilter.matrix([
  0.393, 0.768, 0.189, 0.0, 0.0,
  0.349, 0.686, 0.168, 0.0, 0.0,
  0.272, 0.534, 0.131, 0.0, 0.0,
  0.0, 0.0, 0.0, 1.0, 0.0,
]);

context.pushColorFilter(offset,matrix, (context, offset) {
  paintImage(
    canvas: canvas,
    rect: offset & targetSize,
    image: image,
    fit: BoxFit.fill
  );
});

这些将创建一个新层并对其应用滤色器。