gpt4 book ai didi

dart - 如何在 Flutter 中从 Canvas 中获取 PNG 图片数据?

转载 作者:IT王子 更新时间:2023-10-29 06:34:06 37 4
gpt4 key购买 nike

我有一个 Flutter 小部件,它接受用户输入并使用自定义画家绘制到 Canvas 上:

class SPPoint {
final Point point;
final double size;
SPPoint(this.point, this.size);
String toString() => "SPPoint $point $size";
}

class SignaturePadPainter extends CustomPainter {
final List<SPPoint> allPoints;
final SignaturePadOptions opts;
Canvas _lastCanvas;
Size _lastSize;

SignaturePadPainter(this.allPoints, this.opts);

ui.Image getPng() {
if (_lastCanvas == null) {
return null;
}
if (_lastSize == null) {
return null;
}
var recorder = new ui.PictureRecorder();
var origin = new Offset(0.0, 0.0);
var paintBounds = new Rect.fromPoints(_lastSize.topLeft(origin), _lastSize.bottomRight(origin));
var canvas = new Canvas(recorder, paintBounds);
paint(canvas, _lastSize);
var picture = recorder.endRecording();
return picture.toImage(_lastSize.width.round(), _lastSize.height.round());
}

paint(Canvas canvas, Size size) {
_lastCanvas = canvas;
_lastSize = size;
for (var point in this.allPoints) {
var paint = new Paint()..color = colorFromColorString(opts.penColor);
paint.strokeWidth = 5.0;
var path = new Path();
var offset = new Offset(point.point.x, point.point.y);
path.moveTo(point.point.x, point.point.y);
var pointSize = point.size;
if (pointSize == null || pointSize.isNaN) {
pointSize = opts.dotSize;
}

canvas.drawCircle(offset, pointSize, paint);

paint.style = PaintingStyle.stroke;
canvas.drawPath(path, paint);
}
}

bool shouldRepaint(SignaturePadPainter oldDelegate) {
return true;
}
}

目前 getPng() 返回一个 dart:ui Image 对象,但我不知道如何从图像数据中获取字节(如果这可能的话)

最佳答案

这是我想出的解决方案,现在 toByteData() 已添加到 SDK 中:

var picture = recorder.endRecording();
var image =
picture.toImage(lastSize.width.round(), lastSize.height.round());
ByteData data = await image.toByteData(format: ui.ImageByteFormat.png);
return data.buffer.asUint8List();

此解决方案正在运行,现已作为 signature_pad_flutter 包的一部分发布到 pub:https://github.com/apptreesoftware/signature-pad-dart/blob/master/signature_pad_flutter/lib/src/painter.dart#L17

关于dart - 如何在 Flutter 中从 Canvas 中获取 PNG 图片数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47897130/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com