Created
May 4, 2018 13:53
-
-
Save netsmertia/9c588f23391c781fa1eb791f0dce0768 to your computer and use it in GitHub Desktop.
flutter image drawing in canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:ui' as ui; | |
import 'package:flutter/services.dart' show rootBundle; | |
import 'dart:async'; | |
import 'dart:typed_data'; | |
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> { | |
ui.Image image; | |
bool isImageloaded = false; | |
void initState() { | |
super.initState(); | |
init(); | |
} | |
Future <Null> init() async { | |
final ByteData data = await rootBundle.load('images/lake.jpg'); | |
image = await loadImage(new Uint8List.view(data.buffer)); | |
} | |
Future<ui.Image> loadImage(List<int> img) async { | |
final Completer<ui.Image> completer = new Completer(); | |
ui.decodeImageFromList(img, (ui.Image img) { | |
setState(() { | |
isImageloaded = true; | |
}); | |
return completer.complete(img); | |
}); | |
return completer.future; | |
} | |
Widget _buildImage() { | |
if (this.isImageloaded) { | |
return new CustomPaint( | |
painter: new ImageEditor(image: image), | |
); | |
} else { | |
return new Center(child: new Text('loading')); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
appBar: new AppBar( | |
title: new Text(widget.title), | |
), | |
body: new Container( | |
child: _buildImage(), | |
) | |
); | |
} | |
} | |
class ImageEditor extends CustomPainter { | |
ImageEditor({ | |
this.image, | |
}); | |
ui.Image image; | |
@override | |
void paint(Canvas canvas, Size size) { | |
ByteData data = image.toByteData(); | |
canvas.drawImage(image, new Offset(0.0, 0.0), new Paint()); | |
} | |
@override | |
bool shouldRepaint(CustomPainter oldDelegate) { | |
return false; | |
} | |
} |
hello
after testing your code it seems that something has changed the image loading does not work anymore
these normal?
cdl remy
How can I add the eraser mode on canvas but the eraser should not erase the picture?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot!!