Skip to content

Instantly share code, notes, and snippets.

@speedyGonzales
Created June 29, 2018 08:39
Show Gist options
  • Save speedyGonzales/51d8cd1d94ffe568dddb20759dc9b383 to your computer and use it in GitHub Desktop.
Save speedyGonzales/51d8cd1d94ffe568dddb20759dc9b383 to your computer and use it in GitHub Desktop.
Signature to image transformation
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
void main() => runApp(new MaterialApp(
home: new HomePage(),
debugShowCheckedModeBanner: false,
));
class HomePage extends StatefulWidget {
@override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List<Offset> _points = <Offset>[];
ByteData imgBytes= new ByteData(1024);
void saveToImage(List<Offset> points) async {
final recorder = new ui.PictureRecorder();
final canvas = new Canvas(recorder,
new Rect.fromPoints(new Offset(0.0, 0.0), new Offset(200.0, 200.0)));
Paint paint = new Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i], points[i + 1], paint);
}
}
final picture = recorder.endRecording();
final img = picture.toImage(200, 200);
final pngBytes = await img.toByteData(format: ui.ImageByteFormat.png);
setState(() {
imgBytes = pngBytes;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Container(
child: new GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
setState(() {
RenderBox object = context.findRenderObject();
Offset _localPosition =
object.globalToLocal(details.globalPosition);
_points = new List.from(_points)..add(_localPosition);
});
},
onPanEnd: (DragEndDetails details) => _points.add(null),
child: new CustomPaint(
painter: new Signature(points: _points),
size: new Size(200.0, 200.0),
),
),
),
new Image.memory(new Uint8List.view(imgBytes.buffer)),
],
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.edit),
onPressed: () => saveToImage(_points),
),
);
}
}
class Signature extends CustomPainter {
List<Offset> points; //offset is object with x,y
Signature({this.points});
@override
void paint(Canvas canvas, Size size) {
Paint paint = new Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i], points[i + 1], paint);
}
}
}
@override
bool shouldRepaint(Signature oldDelegate) => oldDelegate.points != points;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment