Flutter 提供了几种基于路径(即剪辑路径)的蒙版方法。我正在尝试找出一种方法,让人们可以像下面的示例那样拍摄带有透明层的图像,并使用该图像来遮盖另一个图像/视图或作为通用遮罩。
我的第一直觉是看 CustomPaint 类,但我无法理解这个最初的想法。
Flutter 有 BoxDecoration 类 接受 BlendMode 枚举。通过利用这些,您可以使用图像实现各种蒙版效果,对于我上面的特殊情况
dstIn
是一个解决方案。
我已经在这里发布了我自己同样问题的答案,使用带有鼠形蒙版和图像的自定义画家类。
@override
void paint(Canvas canvas, Size size) {
if (image != null && mask != null) {
var rect = Rect.fromLTRB(0, 0, 200, 200);
Size outputSize = rect.size;
Paint paint = new Paint();
//Mask
Size maskInputSize = Size(mask.width.toDouble(), mask.height.toDouble());
final FittedSizes maskFittedSizes =
applyBoxFit(BoxFit.cover, maskInputSize, outputSize);
final Size maskSourceSize = maskFittedSizes.source;
final Rect maskSourceRect = Alignment.center
.inscribe(maskSourceSize, Offset.zero & maskInputSize);
canvas.saveLayer(rect, paint);
canvas.drawImageRect(mask, maskSourceRect, rect, paint);
//Image
Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
final FittedSizes fittedSizes =
applyBoxFit(BoxFit.cover, inputSize, outputSize);
final Size sourceSize = fittedSizes.source;
final Rect sourceRect =
Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);
canvas.drawImageRect(
image, sourceRect, rect, paint..blendMode = BlendMode.srcIn);
canvas.restore();
}
}
结果:
这里是将蒙版图像中的任何白色像素转换为主图像中透明像素的示例。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
Image? _image;
Future<void> _loadImage(String maskPath, String imgPath) async {
ByteData data = await rootBundle.load(maskPath);
List<int> bytes = data.buffer.asUint8List();
img.Image mask = img.decodeImage(Uint8List.fromList(bytes))!;
data = await rootBundle.load(imgPath);
bytes = data.buffer.asUint8List();
img.Image image = img.decodeImage(Uint8List.fromList(bytes))!;
for (int y = 0; y < mask.height; y++) {
for (int x = 0; x < mask.width; x++) {
if (mask.getPixel(x, y) == img.getColor(255, 255, 255, 255)) {
image.setPixel(x, y, img.getColor(0, 0, 0, 0));
}
}
}
_image = Image.memory(Uint8List.fromList(img.encodePng(image!)));
}
dependencies:
image: ^3.0.1