简体   繁体   English

Flutter-如何在画布上从相机/画廊绘制图像?

[英]Flutter- How to draw Image from camera/gallery on canvas?

I am learning flutter and came across with drawing image from gallery/camera on canvas using CustomPainter.我正在学习颤振,并使用 CustomPainter 从画布上的画廊/相机中绘制图像。 My code is drawing image , but for some reason it is just showing a small part of whole image(not the complete picture) on the screen.我的代码正在绘制图像,但由于某种原因,它只是在屏幕上显示整个图像的一小部分(不是完整的图片)。

_loadAssetAsImage is being called in initState() function where key is the actual path of the image. _loadAssetAsImageinitState()函数中被调用,其中 key 是图像的实际路径。

void _loadImage( String key ) async {
var data = await rootBundle.load( key );
var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
codec.getNextFrame().then((info){
  setState(() {
    isImageloaded = true;
    image = info.image;
  });
});
  }

Once setState is called, than _buildImage() get called which is in the build() function一旦调用setState ,就会调用build()函数中的_buildImage()

Widget _buildImage() {
if (this.isImageloaded) {
  return new CustomPaint(
      painter: new ImageEditor(image: image),
  );
} else {
  return new Center(child: new Text('loading'));
}
  }

Here ImageEditor is the custom class extending CustomPainter这里ImageEditor是扩展CustomPainter的自定义类

class ImageEditor extends CustomPainter {
  ui.Image image;
  ImageEditor({this.image});

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawImage(image, new Offset(0.0, 0.0),new Paint());
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

Everything looks right to me in here, but not able to understand why only a very small part of Image gets shown on the whole screen instead of full picture.在我看来,这里的一切都是正确的,但无法理解为什么只有非常小的一部分 Image 显示在整个屏幕上而不是全屏上。 Please help me if anyone has a good suggestion on whats missing in the code.如果有人对代码中缺少的内容有好的建议,请帮助我。 在此处输入图片说明

This is what I expected这是我所期望的

在此处输入图片说明 This is what I am getting这就是我得到的

The reason why the canvas only displays a small portion of the image is because the image that's being displayed wasn't scaled down to fit on the widget.画布仅显示图像的一小部分的原因是正在显示的图像没有缩小以适合小部件。 What you can do here is scale the image size when painted on the canvas.您可以在这里做的是在画布上绘制时缩放图像大小。

class ImageEditor extends CustomPainter {

  ...

  @override
  void paint(Canvas canvas, Size size) {
    paintImage(
        canvas: canvas,
        rect: Rect.fromLTWH(0.0, 0.0, scaledWidth, scaledHeight),
        image: image,
        fit: BoxFit.fitWidth);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM