学习一些常用的混合模式之BlendMode.srcIn

58 阅读1分钟

SRC_IN

Keeps the source pixels that cover the destination pixels, discards the remaining source and destination pixels.

计算公式

image.png

大白话就是:在dst透明度是1的时候,重叠部分显示的就是src的内容。非重叠部分src 直接全部丢弃,dst不修改。

第一个例子:

  @override
  void paint(Canvas canvas, Size size) {
    var width = size.width;
    var height = size.height;

    canvas.saveLayer(Rect.fromLTWH(0, 0, width, height), Paint());
    Paint dstPaint = Paint()..color = Colors.red.withOpacity(0.8);
    dstPaint.strokeWidth = 20;
    dstPaint.style = PaintingStyle.stroke;

    canvas.drawCircle(Offset(width/2,height/2), 10, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 50, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 90, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 130, dstPaint);

    var srcPaint = Paint()
      ..color = Colors.blue // 源颜色:蓝色
      ..style = PaintingStyle.stroke // 填充模式
      ..strokeWidth = 50
      ..blendMode = BlendMode.srcIn; // 混合模式
    canvas.drawRect(Rect.fromLTWH(0, 0, width, height), srcPaint);
    // canvas.drawImageRect(image!, Rect.fromLTWH(0, 0, image!.width.toDouble(), image!.height.toDouble()), Rect.fromLTWH(0, 0, width, height), srcPaint);
    canvas.restore();
  }

一个矩形边框跟多个环形进行srcIn混合。效果如下:可以看出重叠部分保留了src,src非重叠部分直接丢弃了。非重叠dst还是保持原样。

image.png

第二个例子:给图形贴纸或者说是图片保留任意部分(只要你能画出路径)

  @override
  void paint(Canvas canvas, Size size) {
    var width = size.width;
    var height = size.height;

    canvas.saveLayer(Rect.fromLTWH(0, 0, width, height), Paint());
    Paint dstPaint = Paint()..color = Colors.red.withOpacity(0.8);
    dstPaint.strokeWidth = 20;
    dstPaint.style = PaintingStyle.stroke;

    canvas.drawCircle(Offset(width/2,height/2), 10, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 50, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 90, dstPaint);

    canvas.drawCircle(Offset(width/2,height/2), 130, dstPaint);

    var srcPaint = Paint()
      ..color = Colors.blue // 源颜色:蓝色
      ..style = PaintingStyle.stroke // 填充模式
      ..strokeWidth = 50
      ..blendMode = BlendMode.srcIn; // 混合模式
    // canvas.drawRect(Rect.fromLTWH(0, 0, width, height), srcPaint);
    canvas.drawImageRect(image!, Rect.fromLTWH(0, 0, image!.width.toDouble(), image!.height.toDouble()), Rect.fromLTWH(0, 0, width, height), srcPaint);
    canvas.restore();
  }

效果图如下:把一张图片贴到了环形上面,如果dst是个圆形,那就是圆形头像。

image.png