Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

draw network image in CustomPainter and save content to file #16

Open
OPY-bbt opened this issue Sep 3, 2019 · 1 comment
Open

draw network image in CustomPainter and save content to file #16

OPY-bbt opened this issue Sep 3, 2019 · 1 comment

Comments

@OPY-bbt
Copy link
Owner

OPY-bbt commented Sep 3, 2019

import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

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

String FILENAME = 'timg.jpeg';

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: PainterPage(), // PosterPage(),
    );
  }
}

class PainterPage extends StatefulWidget {
  @override
  _PainterPageState createState() {
    return _PainterPageState();
  }
}

class _PainterPageState extends State<PainterPage> {
  ImageInfo _imageInfo;
  GlobalKey _containerKey = GlobalKey();

  @override
  void initState() {
    // load Image
    var imgUrl =
        'https://img.tuguaishou.com/ips_templ_preview/0b/66/10/lg_2034979_1566193207_5d5a363796f4e.jpg!w384?auth_key=2199888000-0-0-80d642dfdc7b206f09b718c79547acc8&v=1554825701';
    var img = NetworkImage(imgUrl);
    img.load(img).addListener(
        ImageStreamListener((ImageInfo imageInfo, bool synchronousCall) {
      this.setState(() {
        _imageInfo = imageInfo;
      });
    }));
  }

  _handleSavePressed() async {
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);
    var painter = _PosterPainter(_imageInfo);
    var size = _containerKey.currentContext.size;

    painter.paint(canvas, size);
    ui.Image renderedImage = await recorder
        .endRecording()
        .toImage(size.width.floor(), size.height.floor());

    var pngBytes =
        await renderedImage.toByteData(format: ui.ImageByteFormat.png);

    Directory saveDir = await getApplicationDocumentsDirectory();
    File saveFile = File('${saveDir.path}/$FILENAME');

    if (!saveFile.existsSync()) {
      saveFile.createSync(recursive: true);
    }
    saveFile.writeAsBytesSync(pngBytes.buffer.asUint8List(), flush: true);
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ShowcasePage()),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('制作'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('save'),
        onPressed: _handleSavePressed,
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                key: _containerKey,
                child: CustomPaint(
                  painter: _PosterPainter(_imageInfo),
                  child: Container(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _PosterPainter extends CustomPainter {
  ImageInfo imageInfo;

  _PosterPainter(this.imageInfo);

  paint(Canvas canvas, Size size) {
    canvas.save();
    canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height),
        Paint()..color = Colors.blueGrey);

    canvas.restore();
    if (imageInfo != null) {
      canvas.save();
      canvas.drawImageRect(
        imageInfo.image,
        Rect.fromLTWH(
          0,
          0,
          imageInfo.image.width.toDouble(),
          imageInfo.image.height.toDouble(),
        ),
        Rect.fromLTWH(
          0,
          0,
          size.width,
          imageInfo.image.height.toDouble() /
              (imageInfo.image.width.toDouble() / size.width),
        ),
        Paint(),
      );
      canvas.restore();
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class ShowcasePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('预览'),
      ),
      body: SafeArea(
          child: FutureBuilder(
        future: getApplicationDocumentsDirectory(),
        builder: (BuildContext context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Image.file(File('${snapshot.data.path}/$FILENAME'));
          } else {
            return Container();
          }
        },
      )),
    );
  }
}
@OPY-bbt OPY-bbt changed the title customPainter draw network image and save painter to file draw network image in CustomPainter and save content to file Sep 3, 2019
@OPY-bbt
Copy link
Owner Author

OPY-bbt commented Sep 3, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant