无法在Flutter画布上绘制图像

时间:2020-03-05 13:52:45

标签: flutter canvas dart flutter-canvas

我目前正在尝试在颤动的画布上绘制图像,然后在图像上绘制矩形以覆盖特定数据。我遇到了一个问题,其中矩形绘制得很好,但是图像没有被绘制在后面。看起来好像根本没有被绘制。

我正在将图像从字节加载到Dart UI图像对象中。加载图像后,我创建一个PictureRecorder并将其传递到Canvas对象中。然后,我尝试先绘制图像对象,然后再绘制上方的矩形。完整的代码如下:

import 'dart:async';
import 'dart:typed_data';

import 'dart:ui' as ui;

import 'package:common/ocr/scraped_card_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ObfuscatedCardRenderer {
  ui.Image _backgroundImage;

  ///
  ///
  ///
  Future<ByteData> renderImage(
      Uint8List imageBytes, List<ScrapedCardField> fields) async {
    await _loadImageBackground(imageBytes);
    var obfuscatedImage = await _obfuscateImage(fields);

    var byteD =
        await obfuscatedImage.toByteData(format: ui.ImageByteFormat.png);

    return byteD;
  }

  ///
  ///
  ///
  Future<ui.Image> _obfuscateImage(List<ScrapedCardField> fields) async {
    ui.PictureRecorder recorder = ui.PictureRecorder();
    ui.Canvas c = ui.Canvas(recorder);

    var paint = ui.Paint();

    c.drawImage(_backgroundImage, ui.Offset(0.0, 0.0), new Paint());
    for (ScrapedCardField field in fields) {
      paint.color = Colors.white;
      c.drawRect(field.boundingBox, paint);
    }

    var picture = recorder.endRecording();
    return picture.toImage(_backgroundImage.width, _backgroundImage.height);
  }

  ///
  ///
  ///
  Future<void> _loadImageBackground(Uint8List imageBytes) async {
    if (imageBytes != null) {
      _backgroundImage = await _getImageFromBytes(imageBytes);
    } else {
      return null;
    }
  }

  ///
  ///
  ///
  Future<ui.Image> _getImageFromBytes(Uint8List imageBytes) async {
    var completer = Completer<ui.Image>();
    ui.decodeImageFromList(imageBytes, (image) {
      completer.complete(image);
    });

    return completer.future;
  }
}

结果是:

enter image description here

如您所见,矩形绘制得非常精细,但是背景中的图像不可见。我还应该做些其他事情来绘制图像吗,或者还有另一种方法可以做到这一点?

谢谢!

0 个答案:

没有答案