此附件来自通过画布在本地保存的渲染画布图像。在图像中,我绘制了要在画布中渲染并在本地保存的方形框,没有左右多余的空格。我只想保存方形框并删除不必要的 PNG 图像空间。那么,如何做到这一点呢?
小部件源代码:
return CustomPaint(
painter: PngImageCropper(image: image),
);
PngImageCropper-代码
class PngImageCropper extends CustomPainter {
PngImageCropper({
this.image,
});
ui.Image image;
@override
void paint(Canvas canvas, Size size) {
_drawCanvas(size, canvas);
_saveCanvas(size);
}
Canvas _drawCanvas(Size size, Canvas canvas) {
final center = Offset(image.width / 2, image.height / 2);
double drawImageWidth = 0;
double drawImageHeight = 0;
Rect rect =
Rect.fromCircle(center: center, radius: _getCircularRadius(image));
Path path = Path()..addOval(rect);
canvas.clipPath(path);
Paint paint = new Paint();
canvas.drawImage(
image,
Offset(drawImageWidth, drawImageHeight),
paint,
);
return canvas;
}
_getCircularRadius(ui.Image image) {
return image.height > image.width
? image.width.toDouble() / 2
: image.height.toDouble() / 2;
}
_saveCanvas(Size size) async {
var pictureRecorder = ui.PictureRecorder();
var canvas = Canvas(pictureRecorder);
var paint = Paint();
paint.isAntiAlias = true;
_drawCanvas(size, canvas);
var pic = pictureRecorder.endRecording();
ui.Image img = await pic.toImage(image.width, image.height);
var byteData = await img.toByteData(format: ui.ImageByteFormat.png);
var buffer = byteData.buffer.asUint8List();
// var response = await get(imgUrl);
var documentDirectory = await getApplicationDocumentsDirectory();
File file = File(join(documentDirectory.path,
'${DateTime.now().toUtc().toIso8601String()}.png'));
file.writeAsBytesSync(buffer);
print(file.path);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
}