Barcode Scanner | Xamarin Barcode Scanner
Ready to Use UI Components
The Ready-To-Use UI (RTU UI) Components is an easy way to integrate and customize high-level UI components (View Controllers for iOS and Activities for Android) for the most common tasks in Scanbot Barcode Scanner SDK. The design and behavior of these RTU UI Components are based on our many years of experience as well as the feedback from our SDK customers.
If you need more customization options you have to implement custom screens (View Controllers for iOS and Activities for Android) using our Classic UI Component (not available for Xamarin.Forms).
Barcode Scanner
- Xamarin.Forms
- Xamarin.Droid
- Xamarin.iOS
using ScanbotBarcodeSDK.Forms;
using Xamarin.Forms;
public async void OpenBarcodeScanner() {
var configuration = new BarcodeScannerConfiguration()
{
TopBarBackgroundColor = Color.Red,
AcceptedFormats = new List<BarcodeFormat>()
{
BarcodeFormat.Code25,
BarcodeFormat.Code128,
BarcodeFormat.Aztec
},
// Look up 'BarcodeScannerConfiguration' for many other properties
};
BarcodeResultBundle result = await SBSDK.Scanner.Open(configuration);
// Use the result...
}
Note: this example uses the legacy results API. We also support the new Results API.
using AndroidX.Activity.Result;
using IO.Scanbot.Sdk.Barcode.Entity;
using IO.Scanbot.Sdk.Barcode_scanner;
using IO.Scanbot.Sdk.UI.Barcode_scanner.View.Barcode;
using IO.Scanbot.Sdk.UI.View.Barcode.Configuration;
using IO.Scanbot.Sdk.UI.View.Base;
// Request code for launching the Barcode Scanner Activity and receiving the result
const int BARCODE_DEFAULT_UI_REQUEST_CODE = 1;
void StartBarcodeScannerActivity()
{
var configuration = new BarcodeScannerConfiguration();
configuration.SetTopBarBackgroundColor(Color.Red);
configuration.SetBarcodeFormatsFilter(new List<BarcodeFormat>()
{
BarcodeFormat.Code25,
BarcodeFormat.Code128,
BarcodeFormat.Aztec
});
var intent = BarcodeScannerActivity.NewIntent(this, configuration);
StartActivityForResult(intent, BARCODE_DEFAULT_UI_REQUEST_CODE);
}
// Receiving scan results
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (resultCode != Result.Ok)
{
// The Barcode Scanner screen was closed by the user
return;
}
if (requestCode == BARCODE_DEFAULT_UI_REQUEST_CODE)
{
var barcode = (BarcodeScanningResult) data.GetParcelableExtra(RtuConstants.ExtraKeyRtuResult);
var imagePath = data.GetStringExtra(BarcodeScannerActivity.ScannedBarcodeImagePathExtra);
var previewPath = data.GetStringExtra(BarcodeScannerActivity.ScannedBarcodePreviewFramePathExtra);
//...
}
}
Using the new Results API
The StartActivityForResult
approach has been deprecated for a while now, in favor of the new Results API.
Our SDK supports this new approach, and here's how you can implement it in your project.
Let's use our BarcodeScannerActivity
as an example:
1) Create the result handler class
First we need to create a class that can handle the activity result
using AndroidX.Activity.Result;
using IO.Scanbot.Sdk.UI.Barcode_scanner.View.Barcode;
public class BarcodeScannerResultDelegate : Java.Lang.Object, IActivityResultCallback
{
public void OnActivityResult(Java.Lang.Object result)
{
if (result is BarcodeScannerActivity.BarcodeScannerActivityResult activityResult)
{
if (!activityResult.ResultOk)
{
// The Barcode Scanner screen was closed by the user
return;
}
var imagePath = activityResult.BarcodeImagePath;
var scanningResult = activityResult.GetResult();
var previewPath = scanningResult.PreviewFrame;
var barcodes = scanningResult.BarcodeItems;
// ...
}
}
}
2) Register the activity for result
We need to register the barcode scanner activity for result, from an activity, before OnCreate
is called.
In this example we will use MainActivity.cs
.
Note: our activity must be of type AppCompatActivity
MainActivity.cs
using AndroidX.AppCompat.App;
using AndroidX.Activity.Result;
using IO.Scanbot.Sdk.UI.Barcode_scanner.View.Barcode;
[Activity(MainLauncher = true, Theme = "@style/AppTheme", Icon = "@mipmap/icon")]
public class MainActivity : AppCompatActivity
{
private ActivityResultLauncher barcodeScannerLauncher = RegisterForActivityResult(
new BarcodeScannerActivity.ResultContract(),
new BarcodeScannerResultDelegate() // <-- You could modify the delegate to accept a callback, in order to use the result inside this activity
);
//...
}
3) Launch the activity
using IO.Scanbot.Sdk.UI.View.Barcode.Configuration;
using IO.Scanbot.Sdk.UI.Barcode_scanner.View.Barcode;
public void OpenBarcodeScanner() {
var configuration = new BarcodeScannerConfiguration();
configuration.SetTopBarBackgroundColor(Color.Red);
configuration.SetBarcodeFormatsFilter(new List<BarcodeFormat>()
{
BarcodeFormat.Code25,
BarcodeFormat.Code128,
BarcodeFormat.Aztec
});
// This is the launcher we have created in step 2
barcodeScannerLauncher.Launch(configuration)
}
var configuration = SBSDKUIBarcodeScannerConfiguration.DefaultConfiguration;
configuration.UiConfiguration.TopBarBackgroundColor = UIColor.Red;
configuration.BehaviorConfiguration.AcceptedBarcodeTypes = new SBSDKBarcodeType[]
{
SBSDKBarcodeType.Code25,
SBSDKBarcodeType.Code128,
SBSDKBarcodeType.Aztec
};
var receiver = new BarcodeResultReceiver();
receiver.ResultsReceived += OnScanResultReceived;
SBSDKUIBarcodeScannerViewController.PresentOn(
this, configuration, receiver
);
// Receiving scan results:
public class BarcodeResultReceiver : SBSDKUIBarcodeScannerViewControllerDelegate
{
public override void DidDetectResults(SBSDKUIBarcodeScannerViewController viewController, SBSDKBarcodeScannerResult[] barcodeResults)
{
// Do something with barcodeResults
}
public override void DidCancel(SBSDKUIBarcodeScannerViewController viewController)
{
}
}
For a fully fledged example, please see our example app scanbot-barcode-scanner-sdk-example-xamarin on GitHub.
Batch Barcode Scanner
- Xamarin.Forms
- Xamarin.Droid
- Xamarin.iOS
var configuration = new BatchBarcodeScannerConfiguration
{
TopBarBackgroundColor = Color.Red,
AcceptedFormats = new List<BarcodeFormat>()
{
BarcodeFormat.Code25,
BarcodeFormat.Code128,
BarcodeFormat.Aztec
}
// Look up 'BatchBarcodeScannerConfiguration' for many other properties
};
BarcodeResultBundle result = await SBSDK.Scanner.OpenBatch(config);
var configuration = new BatchBarcodeScannerConfiguration();
configuration.SetTopBarBackgroundColor(Color.Red);
configuration.SetBarcodeFormatsFilter(new List<BarcodeFormat>()
{
BarcodeFormat.Code25,
BarcodeFormat.Code128,
BarcodeFormat.Aztec
});
var intent = BatchBarcodeScannerActivity.NewIntent(this, configuration, null);
StartActivityForResult(intent, BARCODE_DEFAULT_UI_REQUEST_CODE);
// Receiving scan results:
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
var barcode = (BarcodeScanningResult)data.GetParcelableExtra(
RtuConstants.ExtraKeyRtuResult);
var imagePath = data.GetStringExtra(
BaseBarcodeScannerActivity.ScannedBarcodeImagePathExtra);
var previewPath = data.GetStringExtra(
BaseBarcodeScannerActivity.ScannedBarcodePreviewFramePathExtra);
}
var configuration = SBSDKUIBarcodesBatchScannerConfiguration.DefaultConfiguration;
configuration.UiConfiguration.TopBarBackgroundColor = UIColor.Red;
configuration.BehaviorConfiguration.AcceptedBarcodeTypes = new SBSDKBarcodeType[]
{
SBSDKBarcodeType.Code25,
SBSDKBarcodeType.Code128,
SBSDKBarcodeType.Aztec
};
var receiver = new BarcodeBatchResultReceiver();
SBSDKUIBarcodesBatchScannerViewController.PresentOn(
this, configuration, receiver
);
// Receiving scan results:
public class BarcodeBatchResultReceiver : SBSDKUIBarcodesBatchScannerViewControllerDelegate
{
public override void DidDetect(SBSDKUIBarcodesBatchScannerViewController viewController, SBSDKUIBarcodeMappedResult[] barcodeResults)
{
}
}
For a fully fledged example, please see our example app scanbot-barcode-scanner-sdk-example-xamarin on GitHub.
Classic UI Components
Our Classic UI Components allows you to build custom screens which are very flexible and fully customizable. It is a set of easy to integrate and customize components (Views, Buttons, Handlers, Controllers, etc.) which can be embedded and extended in your custom screens.
For more details please see the documentation of our native Barcode Scanner SDKs for iOS and Android as well as our example apps.
For a fully functional example, please see our example app scanbot-barcode-scanner-sdk-example-xamarin on GitHub.
Classic UI Example
- Xamarin.Droid
- Xamarin.iOS
Start by creating a new activity and customizing your layout:
example_barcode_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DemoBarcodeCameraXViewActivity">
<io.scanbot.sdk.ui.camera.ScanbotCameraXView
android:id="@+id/camerax"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="@+id/finder_overlay"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/container_bg" />
<ImageView
android:id="@+id/result"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="bottom|right"
android:contentDescription="snap_result"/>
</FrameLayout>
ExampleBarcodeActivity.cs
1) Make sure to include the Scanbot SDK usings:
using IO.Scanbot.Sdk.Barcode;
using IO.Scanbot.Sdk.Barcode.Entity;
using IO.Scanbot.Sdk.Barcode.UI;
using IO.Scanbot.Sdk.Barcode_scanner;
using IO.Scanbot.Sdk.Camera;
using IO.Scanbot.Sdk.UI.Camera;
//...
2) Inside your namespace declaration, declare your activity and configure permissions check/request
[Activity(Theme = "@style/AppTheme")]
public class ExampleBarcodeActivity : AppCompatActivity
{
ScanbotCameraXView cameraView;
ImageView resultView;
const int REQUEST_PERMISSION_CODE = 200;
public string[] Permissions
{
get => new string[] { Manifest.Permission.Camera };
}
protected override void OnResume()
{
base.OnResume();
var status = ContextCompat.CheckSelfPermission(this, Permissions[0]);
if (status != Permission.Granted)
{
ActivityCompat.RequestPermissions(this, Permissions, REQUEST_PERMISSION_CODE);
}
}
//...
}
3) Create a result handler class
class BarcodeResultDelegate : BarcodeDetectorResultHandlerWrapper
{
public EventHandler<BarcodeScanningResult> Success;
public override bool HandleResult(BarcodeScanningResult result, SdkLicenseError error)
{
if (!MainActivity.SDK.LicenseInfo.IsValid || error != null || result == null)
{
return false;
}
Success?.Invoke(this, result);
return true;
}
}
4) Initialize the SDK components in the activity's OnCreate:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Inflate your XML layout
SetContentView(Resource.Layout.example_barcode_activity);
// Retrieve camera and result view
cameraView = FindViewById<ScanbotCameraXView>(Resource.Id.camerax);
resultView = FindViewById<ImageView>(Resource.Id.result);
// Create Barcode Detector
var barcodeDetector = new ScanbotBarcodeScannerSDK(this).CreateBarcodeDetector();
// Configure Barcode Detector
barcodeDetector.ModifyConfig(new Function1Impl<BarcodeScannerConfigBuilder>((response) => {
response.SetSaveCameraPreviewFrame(true);
response.SetBarcodeFormats(BarcodeTypes.Instance.AcceptedTypes);
}));
// Configure and attach result handler
var resultHandler = new BarcodeResultDelegate();
resultHandler.Success += OnBarcodeResult;
ScanbotCameraViewWrapper.InitDetectionBehavior(cameraView, barcodeDetector, resultHandler, new Java.Lang.Long(1000));
}
private void OnBarcodeResult(object sender, BarcodeEventArgs e)
{
// TODO: Handle your result here
}
Enable continuous focus
For a better user experience, let's also enable continuous focus by implementing ICameraOpenCallback
public class ExampleBarcodeActivity : AppCompatActivity, ICameraOpenCallback
{
public void OnCameraOpened()
{
cameraView.Post(delegate
{
cameraView.ContinuousFocus();
});
}
//...
And setting the callback in the activity OnCreate
protected override void OnCreate(Bundle savedInstanceState)
{
cameraView = FindViewById<ScanbotCameraXView>(Resource.Id.camerax);
cameraView.SetCameraOpenCallback(this);
//...
Auto-snapping
You can also enable auto-snapping to capture a picture everytime a barcode is detected. To do so, let's first define and implement a Picture Callback:
class PictureResultDelegate : PictureCallback
{
class PictureTakenEventArgs : EventArgs
{
public byte[] Image { get; private set; }
public int Orientation { get; private set; }
public PictureTakenEventArgs(byte[] image, int orientation)
{
Image = image;
Orientation = orientation;
}
}
public EventHandler<PictureTakenEventArgs> PictureTaken;
public override void OnPictureTaken(byte[] image, CaptureInfo captureInfo)
{
PictureTaken?.Invoke(this, new PictureTakenEventArgs(image, captureInfo.ImageOrientation));
}
}
Then, in the activity OnCreate
:
protected override void OnCreate(Bundle savedInstanceState)
{
// ...
// Attach snapping controller
var snappingcontroller = BarcodeAutoSnappingController.Attach(cameraView, barcodeDetector);
snappingcontroller.SetSensitivity(1f);
// Add picture delegate
var pictureDelegate = new PictureResultDelegate();
cameraView.AddPictureCallback(pictureDelegate);
pictureDelegate.PictureTaken += OnPictureTaken;
}
public void OnPictureTaken(object sender, PictureTakenEventArgs args)
{
var image = args.Image;
var orientation = args.Orientation;
// Decoding the bytes array
var bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);
if (bitmap == null) { return; }
// Rotating the bitmap according to the image orientation
var matrix = new Matrix();
matrix.SetRotate(orientation, bitmap.Width / 2, bitmap.Height / 2);
var rotatedBitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, false);
// TODO: Here you can use 'rotatedBitmap'
}
You can add SBSDKBarcodeScannerViewController
to a container view, and use it to scan and detect barcodes in real time with the device camera.
public class ClassicScannerController : UIViewController
{
SBSDKBarcodeScannerViewController scannerController;
public override void ViewDidLoad()
{
base.ViewDidLoad();
// We are using `View` (the ViewController main view) as our container view.
scannerController = new SBSDKBarcodeScannerViewController(this, View)
{
// Configure the Barcode Scanner here
// For example:
AcceptedBarcodeTypes = BarcodeTypes.Instance.AcceptedTypes.ToArray()
};
}
}
In order to handle the results, we first need to implement SBSDKBarcodeScannerViewControllerDelegate
. We can create a custom class for that:
public class ClassicScannerReceiver : SBSDKBarcodeScannerViewControllerDelegate
{
public EventHandler<List<SBSDKBarcodeScannerResult>> ResultReceived;
public override void DidDetectBarcodes(SBSDKBarcodeScannerViewController controller, SBSDKBarcodeScannerResult[] codes)
{
ResultReceived?.Invoke(this, codes.ToList());
}
}
We can then set it to our SBSDKBarcodeScannerViewController
instance. Here's the full code:
public class ClassicScannerController : UIViewController
{
SBSDKBarcodeScannerViewController scannerController;
ClassicScannerReceiver receiver;
public override void ViewDidLoad()
{
base.ViewDidLoad();
scannerController = new SBSDKBarcodeScannerViewController(this, View)
{
AcceptedBarcodeTypes = BarcodeTypes.Instance.AcceptedTypes.ToArray()
};
receiver = new ClassicScannerReceiver();
scannerController.Delegate = receiver;
receiver.ResultReceived += OnScanResultReceived;
}
private void OnScanResultReceived(object sender, List<SBSDKBarcodeScannerResult> barcodes)
{
receiver.ResultReceived -= OnScanResultReceived;
// TODO: Handle the result through `barcodes`
}
}
Detection on the Image
Not only can you scan barcodes, the SDK also offers the option to detect barcodes on an existing still image (e.g. JPG file from Photo Library).
- Xamarin.Forms
- Xamarin.Droid
- Xamarin.iOS
List<Barcode> barcodes = await SBSDK.Operations.DetectBarcodesFromImage(DetectBarcodesOnImageConfiguration configuration);
var sdk = new ScanbotBarcodeScannerSDK(this);
BarcodeScanningResult result = sdk.CreateBarcodeDetector().DetectFromBitmap(bitmap, 0);
var scanner = new SBSDKBarcodeScanner(formats);
SBSDKBarcodeScannerResult[] result = scanner.DetectBarCodesOnImage(image);
Want to scan longer than one minute?
Generate a free trial license to test the Scanbot SDK thoroughly.
Get your free Trial LicenseWhat do you think of this documentation?
What can we do to improve it? Please be as detailed as you like.