简体   繁体   English

是否可以用Dart / Flutter绘制图像?

[英]Is it possible to draw an image with Dart/Flutter?

I'm looking to find a path to generating an image (jpeg or png) from within a flutter application. 我正在寻找一个从颤振应用程序中生成图像(jpeg或png)的路径。 The image would be composed of circles, lines, text etc. 图像将由圆,线,文本等组成。

There does appear to be a means of drawing to the screen using a canvas ( https://docs.flutter.io/flutter/dart-ui/Canvas/Canvas.html ), however there doesn't appear to be the equivalent for creating an image that could be presented within or sent/used outside the application. 似乎有一种使用画布绘制到屏幕的方法( https://docs.flutter.io/flutter/dart-ui/Canvas/Canvas.html ),但似乎没有等效的创建可以在应用程序内部呈现或发送/使用的图像。

Is there any dart library available for drawing an image? 有没有可用于绘制图像的dart库? It would seem that it possible given the underlying skia framework. 似乎可以给出底层的skia框架。 In the Dart-html package there is a CanvasRenderingContext2D. 在Dart-html包中有一个CanvasRenderingContext2D。

Edit: Getting something like the following working (as per Richard's suggestions) would be a start: 编辑:获得类似下面的工作(根据理查德的建议)将是一个开始:

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:ui';
import 'dart:typed_data';
import 'dart:async';
import 'dart:io';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Image _image;

  @override
  void initState() {
    super.initState();
    _image = new Image.network(
      'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png',
    );
  }

  Future<String> get _localPath async {
    final directory =
        await getApplicationDocumentsDirectory(); //From path_provider package
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return new File('$path/tempImage.png');
  }

  Future<File> writeImage(ByteData pngBytes) async {
    final file = await _localFile;
    // Write the file
    file.writeAsBytes(pngBytes.buffer.asUint8List());
    return file;
  }

  _generateImage() {
    _generate().then((val) => setState(() {
          _image = val;
        }));
  }

  Future<Image> _generate() async {
    PictureRecorder recorder = new PictureRecorder();
    Canvas c = new Canvas(recorder);
    var rect = new Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
    c.clipRect(rect);

    final paint = new Paint();
    paint.strokeWidth = 2.0;
    paint.color = const Color(0xFF333333);
    paint.style = PaintingStyle.fill;

    final offset = new Offset(50.0, 50.0);
    c.drawCircle(offset, 40.0, paint);
    var picture = recorder.endRecording();

    final pngBytes =
        await picture.toImage(100, 100).toByteData(format: ImageByteFormat.png);

    //Aim #1. Upade _image with generated image.
    var image = Image.memory(pngBytes.buffer.asUint8List());
    return image;

    //new Image.memory(pngBytes.buffer.asUint8List());
    // _image = new Image.network(
    //   'https://github.com/flutter/website/blob/master/_includes/code/layout/lakes/images/lake.jpg?raw=true',
    // );

    //Aim #2. Write image to file system.
    //writeImage(pngBytes);
    //Make a temporary file (see elsewhere on SO) and writeAsBytes(pngBytes.buffer.asUInt8List())
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _image,
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _generateImage,
        tooltip: 'Generate',
        child: new Icon(Icons.add),
      ),
    );
  }
}

PictureRecorder lets you create a Canvas, use the Canvas drawing methods and provides endRecording() returning a Picture . PictureRecorder允许您创建Canvas,使用Canvas绘图方法并提供返回Picture endRecording() You can draw this Picture to other Scenes or Canvases, or use .toImage(width, height).toByteData(format) to convert it to PNG (or raw - jpeg isn't supported). 您可以将此图片绘制到其他场景或画布,或使用.toImage(width, height).toByteData(format)将其转换为PNG(或不支持raw - jpeg)。

For example: 例如:

import 'dart:ui';
import 'dart:typed_data';
....
  PictureRecorder recorder = new PictureRecorder();
  Canvas c = new Canvas(recorder);
  c.drawPaint(paint); // etc
  Picture p = recorder.endRecording();
  ByteData pngBytes =
      await p.toImage(100, 100).toByteData(format: ImageByteFormat.png);

Make sure that you are on flutter 0.4.4, otherwise you may not have the format parameter available. 确保你处于颤振0.4.4,否则你可能没有format参数。

Having seen your edit, though, I suspect you are really looking for CustomPainter where a Widget gives you a Canvas on which you can draw. 但是,看过你的编辑后,我怀疑你真的在寻找CustomPainter ,Widget会为你提供一个Canvas,你可以在其上绘制。 Here's an example from a similar question. 这是一个类似问题的例子

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

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