Flutter-使用PictureRecorder.endRecording()。toImage返回空白图像

时间:2019-01-31 17:10:28

标签: flutter android-canvas flutter-layout drawimage

我正在尝试使用Canvas从两个现有图像创建一个新图像

  1. 从资产中获取一图(“资产图片”)
  2. 来自网络的一图

要实现第一个问题,就是使用drawImage在Canvas上绘制“资产图像”。这是我面临的问题。

drawCircle正常工作,但是要按照以下代码使用drawImage,则会输出空白图像。

我是使用Canvas和进行实验的新手,任何帮助表示赞赏。

完整代码。

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

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;
  ui.Image imagetoDraw;

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

    getImageFromAsset();
  }

  getImageFromAsset() async {
    imagetoDraw = await load('images/loading.png');
    print('...getImageFromAsset done');
  }

  Future<ui.Image> load(String asset) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

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

  Future<Image> _generate() async {
    ui.PictureRecorder recorder = new ui.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); 

    c.drawImage(imagetoDraw, offset, paint);

    var picture = recorder.endRecording();

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

    var image = Image.memory(pngBytes.buffer.asUint8List());
    return image;
  }

  @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),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

图像资产路径似乎是问题所在。我不能肯定地说,因为这里没有pubspec.yaml资产声明。

假设您已在assets: - assets/images/image_01.png - assets/images/image_02.jpg 中添加资产,如下所示:

pubspec.yaml

在这种情况下,您需要指定资产“ assets / images / image_01.png”的路径。 表示imagetoDraw = await load('assets/images/image_01.png');文件中定义的确切路径。

即就您而言,Image.asset('assets/images/image_01.png');

提示:您可以直接使用 String newVersion = null; try { Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en") .timeout(30000) .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") .referrer("http://www.google.com") .get(); if (document != null) { Elements element = document.getElementsContainingOwnText("Current Version"); for (Element ele : element) { if (ele.siblingElements() != null) { Elements sibElemets = ele.siblingElements(); for (Element sibElemet : sibElemets) { newVersion = sibElemet.text(); } } } } if (onlineVersion != null && !onlineVersion.isEmpty()) { if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) { //show anything final String appPackageName = getApplicationContext().getPackageName(); // getPackageName() from Context or Activity object try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName))); } } } 从资产中获取图像。

我引用的来源:Load Image from assets in flutter

我希望这会有所帮助。