Browse Source

implemented multi scan results drawing

pull/76/head
Khoren Markosyan 2 years ago
parent
commit
e56d1fbc79
  1. 274
      example/lib/main.dart
  2. 49
      example/lib/widgets/debug_info_widget.dart
  3. 43
      example/lib/widgets/scan_from_gallery_widget.dart
  4. 46
      example/lib/widgets/scan_mode_dropdown.dart
  5. 46
      example/lib/widgets/scan_result_widget.dart
  6. 15
      example/lib/widgets/unsupported_platform_widget.dart
  7. 10
      lib/flutter_zxing.dart
  8. 4
      lib/generated_bindings.dart
  9. 16
      lib/src/logic/barcodes_reader.dart
  10. 21
      lib/src/models/code.dart
  11. 123
      lib/src/ui/multi_result_overlay.dart
  12. 41
      lib/src/ui/reader_widget.dart
  13. 1
      lib/src/ui/ui.dart
  14. 12
      lib/zxing_mobile.dart
  15. 10
      lib/zxing_web.dart
  16. 11
      src/native_zxing.cpp
  17. 1
      src/native_zxing.h

274
example/lib/main.dart

@ -1,9 +1,12 @@
import 'dart:ui';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart'; import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:image_picker/image_picker.dart';
import 'widgets/debug_info_widget.dart';
import 'widgets/scan_from_gallery_widget.dart';
import 'widgets/scan_mode_dropdown.dart';
import 'widgets/scan_result_widget.dart';
import 'widgets/unsupported_platform_widget.dart';
void main() { void main() {
zx.setLogEnabled(false); zx.setLogEnabled(false);
@ -38,7 +41,10 @@ class _DemoPageState extends State<DemoPage> {
Uint8List? createdCodeBytes; Uint8List? createdCodeBytes;
Code? result; Code? result;
List<Code> multiResult = []; Codes? multiResult;
// Currently code positions works incorrect on Android in Portrait mode
bool isMultiScan = false;
bool showDebugInfo = true; bool showDebugInfo = true;
int successScans = 0; int successScans = 0;
@ -52,8 +58,7 @@ class _DemoPageState extends State<DemoPage> {
length: 2, length: 2,
child: Scaffold( child: Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Flutter Zxing Example'), title: const TabBar(
bottom: const TabBar(
tabs: [ tabs: [
Tab(text: 'Scan Code'), Tab(text: 'Scan Code'),
Tab(text: 'Create Code'), Tab(text: 'Create Code'),
@ -82,34 +87,33 @@ class _DemoPageState extends State<DemoPage> {
onScanFailure: _onScanFailure, onScanFailure: _onScanFailure,
onMultiScan: _onMultiScanSuccess, onMultiScan: _onMultiScanSuccess,
onMultiScanFailure: _onMultiScanFailure, onMultiScanFailure: _onMultiScanFailure,
isMultiScan: false, isMultiScan: isMultiScan,
// showScannerOverlay: false, scanDelay: isMultiScan
// scanDelay: const Duration(milliseconds: 0), ? Duration.zero
// tryInverted: true, : const Duration(milliseconds: 500),
tryInverted: true,
), ),
// show multi results as rectangles
// if (multiResult.isNotEmpty)
// Positioned.fill(
// child: CustomPaint(
// painter: MultiScanPainter(
// codes: multiResult,
// size: Size(
// MediaQuery.of(context).size.width,
// MediaQuery.of(context).size.height,
// ),
// ),
// ),
// ),
ScanFromGalleryWidget( ScanFromGalleryWidget(
onScan: _onScanSuccess, onScan: _onScanSuccess,
onScanFailure: _onScanFailure, onScanFailure: _onScanFailure,
), ),
// Change single/multi scan mode dropdown button
ScanModeDropdown(
isMultiScan: isMultiScan,
onChanged: (value) {
setState(() {
isMultiScan = value;
});
},
),
if (showDebugInfo) if (showDebugInfo)
DebugInfoWidget( DebugInfoWidget(
successScans: successScans, successScans: successScans,
failedScans: failedScans, failedScans: failedScans,
error: result?.error, error: isMultiScan ? multiResult?.error : result?.error,
duration: result?.duration ?? 0, duration: isMultiScan
? multiResult?.duration ?? 0
: result?.duration ?? 0,
onReset: _onReset, onReset: _onReset,
), ),
], ],
@ -133,7 +137,7 @@ class _DemoPageState extends State<DemoPage> {
}, },
), ),
if (createdCodeBytes != null) if (createdCodeBytes != null)
Image.memory(createdCodeBytes ?? Uint8List(0), height: 200), Image.memory(createdCodeBytes ?? Uint8List(0), height: 400),
], ],
), ),
], ],
@ -159,20 +163,20 @@ class _DemoPageState extends State<DemoPage> {
} }
} }
_onMultiScanSuccess(List<Code> codes) { _onMultiScanSuccess(Codes codes) {
setState(() { setState(() {
successScans++; successScans++;
multiResult = codes; multiResult = codes;
}); });
} }
_onMultiScanFailure(List<Code> codes) { _onMultiScanFailure(Codes result) {
setState(() { setState(() {
failedScans++; failedScans++;
multiResult = codes; multiResult = result;
}); });
if (result?.error?.isNotEmpty == true) { if (result.codes.isNotEmpty == true) {
_showMessage(context, 'Error: ${codes.first.error}'); _showMessage(context, 'Error: ${result.codes.first.error}');
} }
} }
@ -190,211 +194,3 @@ class _DemoPageState extends State<DemoPage> {
}); });
} }
} }
class ScanResultWidget extends StatelessWidget {
const ScanResultWidget({
Key? key,
this.result,
this.onScanAgain,
}) : super(key: key);
final Code? result;
final Function()? onScanAgain;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
result?.format?.name ?? '',
style: Theme.of(context).textTheme.headline5,
),
const SizedBox(height: 20),
Text(
result?.text ?? '',
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(height: 20),
Text(
'Inverted: ${result?.isInverted}\t\tMirrored: ${result?.isMirrored}',
style: Theme.of(context).textTheme.bodyText2,
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: onScanAgain,
child: const Text('Scan Again'),
),
],
),
),
);
}
}
class ScanFromGalleryWidget extends StatelessWidget {
const ScanFromGalleryWidget({
Key? key,
this.onScan,
this.onScanFailure,
}) : super(key: key);
final Function(Code)? onScan;
final Function(Code?)? onScanFailure;
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 20,
right: 20,
child: FloatingActionButton(
onPressed: _onFromGalleryButtonTapped,
child: const Icon(Icons.image),
),
);
}
void _onFromGalleryButtonTapped() async {
final XFile? file =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (file != null) {
final Code? result = await zx.readBarcodeImagePath(
file,
params: DecodeParams(tryInverted: true),
);
if (result != null && result.isValid) {
onScan?.call(result);
} else {
result?.error = 'No barcode found';
onScanFailure?.call(result);
}
}
}
}
class DebugInfoWidget extends StatelessWidget {
const DebugInfoWidget({
Key? key,
required this.successScans,
required this.failedScans,
this.error,
this.duration = 0,
this.onReset,
}) : super(key: key);
final int successScans;
final int failedScans;
final String? error;
final int duration;
final Function()? onReset;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.white.withOpacity(0.7),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Success: $successScans\nFailed: $failedScans\nDuration: $duration ms',
style: Theme.of(context).textTheme.bodySmall,
),
TextButton(
onPressed: onReset,
child: const Text('Reset'),
),
],
),
),
),
),
);
}
}
class UnsupportedPlatformWidget extends StatelessWidget {
const UnsupportedPlatformWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'This platform is not supported yet.',
style: Theme.of(context).textTheme.headline6,
),
);
}
}
class MultiResultWidget extends StatelessWidget {
const MultiResultWidget({
super.key,
this.results = const [],
});
final List<Code> results;
@override
Widget build(BuildContext context) {
return Container();
}
}
class MultiScanPainter extends CustomPainter {
MultiScanPainter({
required this.codes,
required this.size,
// required this.scale,
// required this.offset,
});
final List<Code> codes;
final Size size;
final double scale = 1;
final Offset offset = Offset.zero;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = Colors.green
..strokeWidth = 2
..style = PaintingStyle.stroke;
for (final Code code in codes) {
final position = code.position;
if (position == null) {
continue;
}
// position to points
final List<Offset> points = positionToPoints(position);
// debugPrint('w: ${position.imageWidth} h: ${position.imageHeight}');
// print(points);
canvas.drawPoints(PointMode.polygon, points, paint);
}
}
@override
bool shouldRepaint(MultiScanPainter oldDelegate) {
return true;
}
List<Offset> positionToPoints(Position pos) {
return [
Offset(pos.topLeftX.toDouble(), pos.topLeftY.toDouble()),
Offset(pos.topRightX.toDouble(), pos.topRightY.toDouble()),
Offset(pos.bottomRightX.toDouble(), pos.bottomRightY.toDouble()),
Offset(pos.bottomLeftX.toDouble(), pos.bottomLeftY.toDouble()),
];
}
}

49
example/lib/widgets/debug_info_widget.dart

@ -0,0 +1,49 @@
import 'package:flutter/material.dart';
class DebugInfoWidget extends StatelessWidget {
const DebugInfoWidget({
Key? key,
required this.successScans,
required this.failedScans,
this.error,
this.duration = 0,
this.onReset,
}) : super(key: key);
final int successScans;
final int failedScans;
final String? error;
final int duration;
final Function()? onReset;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.white.withOpacity(0.7),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Success: $successScans\nFailed: $failedScans\nDuration: $duration ms',
style: Theme.of(context).textTheme.bodySmall,
),
TextButton(
onPressed: onReset,
child: const Text('Reset'),
),
],
),
),
),
),
);
}
}

43
example/lib/widgets/scan_from_gallery_widget.dart

@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:image_picker/image_picker.dart';
class ScanFromGalleryWidget extends StatelessWidget {
const ScanFromGalleryWidget({
Key? key,
this.onScan,
this.onScanFailure,
}) : super(key: key);
final Function(Code)? onScan;
final Function(Code?)? onScanFailure;
@override
Widget build(BuildContext context) {
return Positioned(
bottom: 20,
right: 20,
child: FloatingActionButton(
onPressed: _onFromGalleryButtonTapped,
child: const Icon(Icons.image),
),
);
}
void _onFromGalleryButtonTapped() async {
final XFile? file =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (file != null) {
final Code? result = await zx.readBarcodeImagePath(
file,
params: DecodeParams(tryInverted: true),
);
if (result != null && result.isValid) {
onScan?.call(result);
} else {
result?.error = 'No barcode found';
onScanFailure?.call(result);
}
}
}
}

46
example/lib/widgets/scan_mode_dropdown.dart

@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
class ScanModeDropdown extends StatelessWidget {
const ScanModeDropdown({
Key? key,
this.isMultiScan = false,
this.onChanged,
}) : super(key: key);
final bool isMultiScan;
final Function(bool value)? onChanged;
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<bool>(
value: isMultiScan,
items: const [
DropdownMenuItem(
value: false,
child: Text('Single Scan'),
),
DropdownMenuItem(
value: true,
child: Text('Multi Scan'),
),
],
onChanged: (value) => onChanged?.call(value ?? false),
),
),
),
),
);
}
}

46
example/lib/widgets/scan_result_widget.dart

@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart';
class ScanResultWidget extends StatelessWidget {
const ScanResultWidget({
Key? key,
this.result,
this.onScanAgain,
}) : super(key: key);
final Code? result;
final Function()? onScanAgain;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
result?.format?.name ?? '',
style: Theme.of(context).textTheme.headline5,
),
const SizedBox(height: 20),
Text(
result?.text ?? '',
style: Theme.of(context).textTheme.headline6,
),
const SizedBox(height: 20),
Text(
'Inverted: ${result?.isInverted}\t\tMirrored: ${result?.isMirrored}',
style: Theme.of(context).textTheme.bodyText2,
),
const SizedBox(height: 40),
ElevatedButton(
onPressed: onScanAgain,
child: const Text('Scan Again'),
),
],
),
),
);
}
}

15
example/lib/widgets/unsupported_platform_widget.dart

@ -0,0 +1,15 @@
import 'package:flutter/material.dart';
class UnsupportedPlatformWidget extends StatelessWidget {
const UnsupportedPlatformWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'This platform is not supported yet.',
style: Theme.of(context).textTheme.headline6,
),
);
}
}

10
lib/flutter_zxing.dart

@ -39,7 +39,7 @@ abstract class Zxing {
}); });
/// Reads barcodes from the camera /// Reads barcodes from the camera
Future<List<Code>> processCameraImageMulti( Future<Codes> processCameraImageMulti(
CameraImage image, { CameraImage image, {
DecodeParams? params, DecodeParams? params,
}); });
@ -71,25 +71,25 @@ abstract class Zxing {
}); });
/// Reads barcodes from String image path /// Reads barcodes from String image path
Future<List<Code>> readBarcodesImagePathString( Future<Codes> readBarcodesImagePathString(
String path, { String path, {
DecodeParams? params, DecodeParams? params,
}); });
/// Reads barcodes from XFile image path /// Reads barcodes from XFile image path
Future<List<Code>> readBarcodesImagePath( Future<Codes> readBarcodesImagePath(
XFile path, { XFile path, {
DecodeParams? params, DecodeParams? params,
}); });
/// Reads barcodes from image url /// Reads barcodes from image url
Future<List<Code>> readBarcodesImageUrl( Future<Codes> readBarcodesImageUrl(
String url, { String url, {
DecodeParams? params, DecodeParams? params,
}); });
/// Reads barcodes from Uint8List image bytes /// Reads barcodes from Uint8List image bytes
List<Code> readBarcodes( Codes readBarcodes(
Uint8List bytes, { Uint8List bytes, {
required int width, required int width,
required int height, required int height,

4
lib/generated_bindings.dart

@ -263,6 +263,10 @@ class CodeResults extends ffi.Struct {
/// < The results of the barcode decoding /// < The results of the barcode decoding
external ffi.Pointer<CodeResult> results; external ffi.Pointer<CodeResult> results;
/// < The duration of the decoding in milliseconds
@ffi.Int()
external int duration;
} }
/// @brief EncodeResult encapsulates the result of encoding a barcode. /// @brief EncodeResult encapsulates the result of encoding a barcode.

16
lib/src/logic/barcodes_reader.dart

@ -1,7 +1,7 @@
part of 'zxing.dart'; part of 'zxing.dart';
/// Reads barcodes from String image path /// Reads barcodes from String image path
Future<List<Code>> zxingReadBarcodesImagePathString( Future<Codes> zxingReadBarcodesImagePathString(
String path, { String path, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
@ -11,14 +11,14 @@ Future<List<Code>> zxingReadBarcodesImagePathString(
); );
/// Reads barcodes from XFile image path /// Reads barcodes from XFile image path
Future<List<Code>> zxingReadBarcodesImagePath( Future<Codes> zxingReadBarcodesImagePath(
XFile path, { XFile path, {
DecodeParams? params, DecodeParams? params,
}) async { }) async {
final Uint8List imageBytes = await path.readAsBytes(); final Uint8List imageBytes = await path.readAsBytes();
imglib.Image? image = imglib.decodeImage(imageBytes); imglib.Image? image = imglib.decodeImage(imageBytes);
if (image == null) { if (image == null) {
return <Code>[]; return Codes(<Code>[], 0);
} }
image = resizeToMaxSize(image, params?.maxSize); image = resizeToMaxSize(image, params?.maxSize);
return zxingReadBarcodes( return zxingReadBarcodes(
@ -30,7 +30,7 @@ Future<List<Code>> zxingReadBarcodesImagePath(
} }
/// Reads barcodes from image url /// Reads barcodes from image url
Future<List<Code>> zxingReadBarcodesImageUrl( Future<Codes> zxingReadBarcodesImageUrl(
String url, { String url, {
DecodeParams? params, DecodeParams? params,
}) async { }) async {
@ -38,7 +38,7 @@ Future<List<Code>> zxingReadBarcodesImageUrl(
(await NetworkAssetBundle(Uri.parse(url)).load(url)).buffer.asUint8List(); (await NetworkAssetBundle(Uri.parse(url)).load(url)).buffer.asUint8List();
imglib.Image? image = imglib.decodeImage(imageBytes); imglib.Image? image = imglib.decodeImage(imageBytes);
if (image == null) { if (image == null) {
return <Code>[]; return Codes(<Code>[], 0);
} }
image = resizeToMaxSize(image, params?.maxSize); image = resizeToMaxSize(image, params?.maxSize);
return zxingReadBarcodes( return zxingReadBarcodes(
@ -50,7 +50,7 @@ Future<List<Code>> zxingReadBarcodesImageUrl(
} }
/// Reads barcodes from Uint8List image bytes /// Reads barcodes from Uint8List image bytes
List<Code> zxingReadBarcodes( Codes zxingReadBarcodes(
Uint8List bytes, { Uint8List bytes, {
required int width, required int width,
required int height, required int height,
@ -59,7 +59,7 @@ List<Code> zxingReadBarcodes(
return _readBarcodes(bytes, width, height, params); return _readBarcodes(bytes, width, height, params);
} }
List<Code> _readBarcodes( Codes _readBarcodes(
Uint8List bytes, Uint8List bytes,
int width, int width,
int height, int height,
@ -80,5 +80,5 @@ List<Code> _readBarcodes(
for (int i = 0; i < result.count; i++) { for (int i = 0; i < result.count; i++) {
results.add(result.results.elementAt(i).ref.toCode()); results.add(result.results.elementAt(i).ref.toCode());
} }
return results; return Codes(results, result.duration);
} }

21
lib/src/models/code.dart

@ -26,3 +26,24 @@ class Code {
bool isMirrored; // Whether the code is mirrored bool isMirrored; // Whether the code is mirrored
int duration; // The duration of the decoding in milliseconds int duration; // The duration of the decoding in milliseconds
} }
// Represents a list of barcode codes
class Codes {
Codes(
this.codes,
this.duration,
);
List<Code> codes; // The list of codes
int duration; // The duration of the decoding in milliseconds
// Returns the first code error if any
String? get error {
for (final Code code in codes) {
if (code.error != null) {
return code.error;
}
}
return null;
}
}

123
lib/src/ui/multi_result_overlay.dart

@ -0,0 +1,123 @@
import 'dart:ui';
import 'package:flutter/material.dart';
import '../../flutter_zxing.dart';
class MultiResultOverlay extends StatelessWidget {
const MultiResultOverlay({
super.key,
this.results = const <Code>[],
this.onCodeTap,
});
final List<Code> results;
final Function(Code code)? onCodeTap;
@override
Widget build(BuildContext context) {
return Positioned.fill(
child: CustomPaint(
painter: MultiScanPainter(
context: context,
codes: results,
color: Theme.of(context).primaryColor,
onCodeTap: onCodeTap,
),
),
);
}
}
class MultiScanPainter extends CustomPainter {
MultiScanPainter({
required this.context,
required this.codes,
this.onCodeTap,
this.offset = Offset.zero,
this.color = Colors.blue,
});
final BuildContext context;
final List<Code> codes;
final Offset offset;
final Color color;
final Function(Code code)? onCodeTap;
final Map<Rect, Code> _codeRects = <Rect, Code>{};
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = color
..strokeWidth = 3
..style = PaintingStyle.stroke;
for (final Code code in codes) {
final Position? position = code.position;
if (position == null) {
continue;
}
final double scale = size.width / position.imageWidth;
// position to points
final List<Offset> points = positionToPoints(position);
final List<Offset> scaledPoints = points
.map((Offset point) => Offset(
point.dx * scale + offset.dx,
point.dy * scale + offset.dy,
))
.toList();
canvas.drawPoints(PointMode.polygon, scaledPoints, paint);
final Rect rect = Rect.fromPoints(scaledPoints[0], scaledPoints[2]);
final TextPainter textPainter = TextPainter(
text: TextSpan(
text: code.text,
style: TextStyle(
color: color,
fontSize: 12,
),
),
maxLines: 2,
textDirection: TextDirection.ltr,
)..layout();
textPainter.layout(maxWidth: rect.width);
textPainter.paint(canvas, rect.topLeft.translate(0, -textPainter.height));
_codeRects[rect] = code;
}
}
@override
bool? hitTest(Offset position) {
for (final Rect rect in _codeRects.keys) {
if (rect.contains(position)) {
final Code? code = _codeRects[rect];
if (code != null) {
onCodeTap?.call(code);
}
return false;
}
}
return super.hitTest(position);
}
@override
bool shouldRepaint(MultiScanPainter oldDelegate) {
return true;
}
List<Offset> positionToPoints(Position pos) {
return <Offset>[
Offset(pos.topLeftX.toDouble(), pos.topLeftY.toDouble()),
Offset(pos.topRightX.toDouble(), pos.topRightY.toDouble()),
Offset(pos.bottomRightX.toDouble(), pos.bottomRightY.toDouble()),
Offset(pos.bottomLeftX.toDouble(), pos.bottomLeftY.toDouble()),
Offset(pos.topLeftX.toDouble(), pos.topLeftY.toDouble()),
];
}
}

41
lib/src/ui/reader_widget.dart

@ -24,8 +24,8 @@ class ReaderWidget extends StatefulWidget {
this.scannerOverlay, this.scannerOverlay,
this.showFlashlight = true, this.showFlashlight = true,
this.allowPinchZoom = true, this.allowPinchZoom = true,
this.scanDelay = const Duration(milliseconds: 1000), // 1000ms delay this.scanDelay = const Duration(milliseconds: 1000),
this.scanDelaySuccess = const Duration(milliseconds: 1000), // 1000ms delay this.scanDelaySuccess = const Duration(milliseconds: 1000),
this.cropPercent = 0.5, // 50% of the screen this.cropPercent = 0.5, // 50% of the screen
this.resolution = ResolutionPreset.high, this.resolution = ResolutionPreset.high,
this.loading = this.loading =
@ -39,10 +39,10 @@ class ReaderWidget extends StatefulWidget {
final Function(Code)? onScanFailure; final Function(Code)? onScanFailure;
/// Called when a code is detected /// Called when a code is detected
final Function(List<Code>)? onMultiScan; final Function(Codes)? onMultiScan;
/// Called when a code is not detected /// Called when a code is not detected
final Function(List<Code>)? onMultiScanFailure; final Function(Codes)? onMultiScanFailure;
/// Called when the camera controller is created /// Called when the camera controller is created
final Function(CameraController?)? onControllerCreated; final Function(CameraController?)? onControllerCreated;
@ -74,13 +74,13 @@ class ReaderWidget extends StatefulWidget {
/// Delay between scans when no code is detected /// Delay between scans when no code is detected
final Duration scanDelay; final Duration scanDelay;
/// Crop percent of the screen /// Crop percent of the screen, will be ignored if isMultiScan is true
final double cropPercent; final double cropPercent;
/// Camera resolution /// Camera resolution
final ResolutionPreset resolution; final ResolutionPreset resolution;
/// Delay between scans when a code is detected /// Delay between scans when a code is detected, will be ignored if isMultiScan is true
final Duration scanDelaySuccess; final Duration scanDelaySuccess;
/// Loading widget while camera is initializing. Default is a black screen /// Loading widget while camera is initializing. Default is a black screen
@ -106,6 +106,8 @@ class _ReaderWidgetState extends State<ReaderWidget>
// true when code detecting is ongoing // true when code detecting is ongoing
bool _isProcessing = false; bool _isProcessing = false;
Codes results = Codes(<Code>[], 0);
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -209,8 +211,7 @@ class _ReaderWidgetState extends State<ReaderWidget>
if (!_isProcessing) { if (!_isProcessing) {
_isProcessing = true; _isProcessing = true;
try { try {
final double cropPercent = final double cropPercent = widget.isMultiScan ? 0 : widget.cropPercent;
widget.showScannerOverlay ? widget.cropPercent : 0;
final int cropSize = final int cropSize =
(min(image.width, image.height) * cropPercent).round(); (min(image.width, image.height) * cropPercent).round();
final DecodeParams params = DecodeParams( final DecodeParams params = DecodeParams(
@ -222,16 +223,20 @@ class _ReaderWidgetState extends State<ReaderWidget>
isMultiScan: widget.isMultiScan, isMultiScan: widget.isMultiScan,
); );
if (widget.isMultiScan) { if (widget.isMultiScan) {
final List<Code> results = await zx.processCameraImageMulti( final Codes result = await zx.processCameraImageMulti(
image, image,
params: params, params: params,
); );
if (results.isNotEmpty) { if (result.codes.isNotEmpty) {
widget.onMultiScan?.call(results); results = result;
await Future<void>.delayed(widget.scanDelaySuccess); widget.onMultiScan?.call(result);
setState(() {}); setState(() {});
if (!widget.isMultiScan) {
await Future<void>.delayed(widget.scanDelaySuccess);
}
} else { } else {
widget.onMultiScanFailure?.call(results); results = Codes(<Code>[], 0);
widget.onMultiScanFailure?.call(result);
} }
} else { } else {
final Code result = await zx.processCameraImage( final Code result = await zx.processCameraImage(
@ -282,13 +287,21 @@ class _ReaderWidgetState extends State<ReaderWidget>
width: cameraMaxSize, width: cameraMaxSize,
child: CameraPreview( child: CameraPreview(
controller!, controller!,
child: widget.showScannerOverlay &&
widget.isMultiScan &&
results.codes.isNotEmpty
? MultiResultOverlay(
results: results.codes,
onCodeTap: widget.onScan,
)
: null,
), ),
), ),
), ),
), ),
), ),
), ),
if (widget.showScannerOverlay) if (widget.showScannerOverlay && !widget.isMultiScan)
Container( Container(
decoration: ShapeDecoration( decoration: ShapeDecoration(
shape: widget.scannerOverlay ?? shape: widget.scannerOverlay ??

1
lib/src/ui/ui.dart

@ -1,5 +1,6 @@
export 'dynamic_scanner_overlay.dart'; export 'dynamic_scanner_overlay.dart';
export 'fixed_scanner_overlay.dart'; export 'fixed_scanner_overlay.dart';
export 'multi_result_overlay.dart';
export 'reader_widget.dart'; export 'reader_widget.dart';
export 'scanner_overlay.dart'; export 'scanner_overlay.dart';
export 'writer_widget.dart'; export 'writer_widget.dart';

12
lib/zxing_mobile.dart

@ -46,11 +46,11 @@ class ZxingMobile implements Zxing {
await zxingProcessCameraImage(image, params: params) as Code; await zxingProcessCameraImage(image, params: params) as Code;
@override @override
Future<List<Code>> processCameraImageMulti( Future<Codes> processCameraImageMulti(
CameraImage image, { CameraImage image, {
DecodeParams? params, DecodeParams? params,
}) async => }) async =>
await zxingProcessCameraImage(image, params: params) as List<Code>; await zxingProcessCameraImage(image, params: params) as Codes;
@override @override
Future<Code?> readBarcodeImagePathString( Future<Code?> readBarcodeImagePathString(
@ -83,28 +83,28 @@ class ZxingMobile implements Zxing {
zxingReadBarcode(bytes, width: width, height: height, params: params); zxingReadBarcode(bytes, width: width, height: height, params: params);
@override @override
Future<List<Code>> readBarcodesImagePathString( Future<Codes> readBarcodesImagePathString(
String path, { String path, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
zxingReadBarcodesImagePathString(path, params: params); zxingReadBarcodesImagePathString(path, params: params);
@override @override
Future<List<Code>> readBarcodesImagePath( Future<Codes> readBarcodesImagePath(
XFile path, { XFile path, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
zxingReadBarcodesImagePath(path, params: params); zxingReadBarcodesImagePath(path, params: params);
@override @override
Future<List<Code>> readBarcodesImageUrl( Future<Codes> readBarcodesImageUrl(
String url, { String url, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
zxingReadBarcodesImageUrl(url, params: params); zxingReadBarcodesImageUrl(url, params: params);
@override @override
List<Code> readBarcodes( Codes readBarcodes(
Uint8List bytes, { Uint8List bytes, {
required int width, required int width,
required int height, required int height,

10
lib/zxing_web.dart

@ -39,7 +39,7 @@ class ZxingWeb implements Zxing {
throw UnimplementedError(); throw UnimplementedError();
@override @override
Future<List<Code>> processCameraImageMulti( Future<Codes> processCameraImageMulti(
CameraImage image, { CameraImage image, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
@ -76,28 +76,28 @@ class ZxingWeb implements Zxing {
throw UnimplementedError(); throw UnimplementedError();
@override @override
Future<List<Code>> readBarcodesImagePathString( Future<Codes> readBarcodesImagePathString(
String path, { String path, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
throw UnimplementedError(); throw UnimplementedError();
@override @override
Future<List<Code>> readBarcodesImagePath( Future<Codes> readBarcodesImagePath(
XFile path, { XFile path, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
throw UnimplementedError(); throw UnimplementedError();
@override @override
Future<List<Code>> readBarcodesImageUrl( Future<Codes> readBarcodesImageUrl(
String url, { String url, {
DecodeParams? params, DecodeParams? params,
}) => }) =>
throw UnimplementedError(); throw UnimplementedError();
@override @override
List<Code> readBarcodes( Codes readBarcodes(
Uint8List bytes, { Uint8List bytes, {
required int width, required int width,
required int height, required int height,

11
src/native_zxing.cpp

@ -40,7 +40,7 @@ extern "C"
{ {
image = image.cropped(width / 2 - cropWidth / 2, height / 2 - cropHeight / 2, cropWidth, cropHeight); image = image.cropped(width / 2 - cropWidth / 2, height / 2 - cropHeight / 2, cropWidth, cropHeight);
} }
DecodeHints hints = DecodeHints().setTryHarder(tryHarder).setTryRotate(tryRotate).setFormats(BarcodeFormat(format)).setTryInvert(tryInvert); DecodeHints hints = DecodeHints().setTryHarder(tryHarder).setTryRotate(tryRotate).setFormats(BarcodeFormat(format)).setTryInvert(tryInvert).setReturnErrors(true);
Result result = ReadBarcode(image, hints); Result result = ReadBarcode(image, hints);
struct CodeResult code; struct CodeResult code;
@ -71,9 +71,12 @@ extern "C"
{ {
image = image.cropped(width / 2 - cropWidth / 2, height / 2 - cropHeight / 2, cropWidth, cropHeight); image = image.cropped(width / 2 - cropWidth / 2, height / 2 - cropHeight / 2, cropWidth, cropHeight);
} }
DecodeHints hints = DecodeHints().setTryHarder(tryHarder).setTryRotate(tryRotate).setFormats(BarcodeFormat(format)).setTryInvert(tryInvert); DecodeHints hints = DecodeHints().setTryHarder(tryHarder).setTryRotate(tryRotate).setFormats(BarcodeFormat(format)).setTryInvert(tryInvert).setReturnErrors(true);
Results results = ReadBarcodes(image, hints); Results results = ReadBarcodes(image, hints);
// remove invalid results
results.erase(remove_if(results.begin(), results.end(), [](Result const &result) { return !result.isValid(); }), results.end());
int evalInMillis = static_cast<int>(get_now() - start); int evalInMillis = static_cast<int>(get_now() - start);
platform_log("Read Barcode in: %d ms\n", evalInMillis); platform_log("Read Barcode in: %d ms\n", evalInMillis);
@ -91,7 +94,7 @@ extern "C"
} }
delete[] data; delete[] data;
delete[] bytes; delete[] bytes;
return {i, codes}; return {i, codes, evalInMillis};
} }
FUNCTION_ATTRIBUTE FUNCTION_ATTRIBUTE
@ -143,7 +146,7 @@ extern "C"
auto tr = p.topRight(); auto tr = p.topRight();
auto bl = p.bottomLeft(); auto bl = p.bottomLeft();
auto br = p.bottomRight(); auto br = p.bottomRight();
code->pos = new Pos{tl.x, tl.y, tr.x, tr.y, bl.x, bl.y, br.x, br.y}; code->pos = new Pos{0, 0, tl.x, tl.y, tr.x, tr.y, bl.x, bl.y, br.x, br.y};
code->isInverted = result.isInverted(); code->isInverted = result.isInverted();
code->isMirrored = result.isMirrored(); code->isMirrored = result.isMirrored();

1
src/native_zxing.h

@ -45,6 +45,7 @@ extern "C"
{ {
int count; ///< The number of barcodes detected int count; ///< The number of barcodes detected
struct CodeResult *results; ///< The results of the barcode decoding struct CodeResult *results; ///< The results of the barcode decoding
int duration; ///< The duration of the decoding in milliseconds
}; };
/** /**

Loading…
Cancel
Save