Olá, neste post irei demonstrar como criar um scanner de barcode em aplicações Xamarin.Forms. Com esse scanner será possível ler os seguintes tipos de códigos:
- Aztec
- Code 128
- Code 39
- Code 93
- EAN13
- EAN8
- PDF417
- QR
- UPC-E
ADICIONANDO O NUGET PACKAGE
Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”
Digite “Zxing.Net.Mobile” e selecione o plugin como demonstrado na imagem a seguir.
Selecione todos os projetos e clique no botão “Install”.
Xaml
Crie um botão para acionar o scanner, na propriedade “Clicked” adicione uma chamada para o método “OpenScanner”.
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
… | |
<ContentPage.Content> | |
<StackLayout> | |
<Button Text="Open Scanner" Clicked="OpenScanner"/> | |
</StackLayout> | |
</ContentPage.Content> | |
… |
CODE-BEHIND
Crie o método “Scanner” que será chamado pelo método “OpenScanner”.
No método “Scanner” crie uma ZXingScannerPage, que será responsável por realizar a leitura do barcode, assim que obtiver um resultado irá parar de escanear e demonstra-lo em um DisplayAlert.
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
private void OpenScanner(object sender, EventArgs e) | |
{ | |
Scanner(); | |
} | |
public async void Scanner() | |
{ | |
var ScannerPage = new ZXingScannerPage(); | |
ScannerPage.OnScanResult += (result) => { | |
// Parar de escanear | |
ScannerPage.IsScanning = false; | |
// Alert com o código escaneado | |
Device.BeginInvokeOnMainThread(() => { | |
Navigation.PopAsync(); | |
DisplayAlert("Código escaneado", result.Text, "OK"); | |
}); | |
}; | |
await Navigation.PushAsync(ScannerPage); | |
} | |
CONFIGURAÇÕES DA PLATAFORMA
É necessário realizar algumas configurações de acordo com cada plataforma, para definir permissões e etc…
Android
Edite o manifesto para adicionar algumas permissões, para isso clique com o botão direito no projeto .android e selecione Properties.
No Android Manifest selecione “CAMERA”, assim terá permissão para acionar a câmera do dispositivo.
MainActivity.cs
No arquivo MainActivity sobrescreva o método “OnRequestPermissionsResult” como demonstrado a seguir.
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
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) | |
{ | |
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults); | |
} |
iOS
Adicionar permissões para que o seu app acesse a câmera na plataforma iOS é necessário editar o arquivo Info.plist que encontra-se no seu projeto .iOS
No arquivo Info.plist adicione a chave NSCameraUsageDescription como demonstrado a seguir.
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
… | |
</array> | |
<key>UILaunchStoryboardName</key> | |
<string>LaunchScreen</string> | |
<key>NSCameraUsageDescription</key> | |
<string>This app needs to access a camera to scan the barcode.</string> | |
</dict> | |
</plist> |
AppDelegate.cs
No arquivo AppDelegate inicialize o ZXing adicionando a linha de código demonstrada a seguir dentro do método FinishedLaunching.
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
public override bool FinishedLaunching(UIApplication app, NSDictionary options) | |
{ | |
global::Xamarin.Forms.Forms.Init(); | |
LoadApplication(new App()); | |
//Inicializa o Zxing no iOS | |
ZXing.Net.Mobile.Forms.iOS.Platform.Init(); | |
return base.FinishedLaunching(app, options); | |
} |
Resultado
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.
Muito bom, parabéns!
CurtirCurtir
Obrigado 🙂
CurtirCurtir
Juliano, talvez para facilitar os usuário que irão ler esse post, deixo registrado que para funcionar esse exemplo, é necessário que o App seja baseado em uma NavigationPage. Informá-lo na classe App.
ex:
MainPage = new NavigationPage(new BarcodeScanner.MainPage());
CurtirCurtir
Bem observado Marcio, obrigado 🙂
CurtirCurtir
Hi,
I’m new on mobile programming,
my question will be obvious to you…
I would like to change your QR-Code-Scanner-Xamarin.Forms sample,
I need to add a textbox to main page,
and the barcode instead of being displayed in a popup it is put in the textbox.
Can you help me ?
CurtirCurtir
Hi Mark,
Yes I can 😀
First, create a Entry in your page:
After, in your method scanner use:
Device.BeginInvokeOnMainThread(() => {
Navigation.PopAsync();
yourEntry.Text = result.Text;
});
Hope this helps.
CurtirCurtir
hy. Thanx for article. But I get error after installing ZXing: “Package ‘ZXing.Net.Mobile 2.3.2’ was restored using ‘.NETFramework,Version=v4.6.1’ instead of the project target framework ‘.NETStandard,Version=v2.0’. This package may not be fully compatible with your project. ” I look at propreties and it does targets to v2.0. Then why do project is being created as .NET4.6, but restores as v2.0 instead ? what is the point? confusing.. Btw, I got errors after trying to “Live Run”: 1. The name ‘ZXing’ does not exist in the current context.2. The type or namespace name ‘ZXing’ could not be found .3. The type or namespace name ‘ZXingScannerPage’ could not be found. Each error suggest to check if I may be missing directives or assemblies though instelisense works very well and project builds up without errors. Error arrise when trying to run. Hope to hear from you. Thanx.
CurtirCurtir
Hi Tom,
In the moment the ZXing not support .NET Standard
Look this workaround in the link
https://github.com/Redth/ZXing.Net.Mobile/issues/578
I hope help you.
CurtirCurtir
Hello.
Thanks for your nice article.
How I can add Toggle torch button to Scanner View.
Thank you.
Merry Christmas.
CurtirCurtir
Hello Ramin,
Thanks, i’m happy in see that my posts its help you.
Try use ScannerPage.ToggleTorch(); but i think not have button for ZXingScannerPage.
I hope help you.
Merry Christmas.
CurtirCurtir
Hi,
I am working based on your tutorial..
In project i am using pcl , not shared project
I got the warning like
Package ‘ZXing.Net.Mobile 2.3.2’ was restored using ‘.NETFramework,Version=v4.6.1’ instead of the project target framework ‘.NETStandard,Version=v2.0’. This package may not be fully compatible with your project.
Please help me..
How Can I solve this.
CurtirCurtir
Hi Siva,
In the moment this nuget package show warning, but this work normally.
I believe that in the future this nuget to be update.
CurtirCurtir
Parabens Juliano. Sou professor da FATEC ZL em Sao Paulo e gostei do seu POST
CurtirCurtir
Obrigado Joilson 🙂
Fico feliz em saber disso, me formei pela FATEC de Sorocaba.
Se precisarem de alguma palestra ai na FATEC ZL me coloco a disposição.
Abraço
CurtirCurtir
Hi Juliano,
Thanks for your post and sample. I was looking for QR-Code scanner for Xamarin and ended up here.
When I clone your repo and run, it works perfectly fine but when I start a new project and follow every steps as you said I got an error when I run it at
LoadApplication(new App());
in MainActivity in my Android project.
Error :
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object. occurred
Im using
Visual Studio Community 2017 Version 15.5.7
Windows 10
Google Nexus 5 connected via cable
I noticed you have a package “FastAndroidCamera” but you didnt mention in your steps.
I even tried installing same Xamarin version you have 2.3.4.270 but it didnt help.
Any Idea? Can you please help me?
Thanks in advance
Hovik
CurtirCurtir
hey Juliano, Sorry it did a small mistake that caused that error. Works fine now.
Thanks for sample again.
Keep going…
CurtirCurtir
Hello … Do not worry. I’m Happy to you solved your problem 🙂
CurtirCurtir
Estou com o mesmo problema do Hovik. Qual a solução?
CurtirCurtir
Olá Allan,
Verifique se todas as variáveis estão sendo inicializadas.
CurtirCurtir
Bom dia Juliano, estou testando com um tablet Android 4.4, e a leitura não é realizada, testei em outro celular Samsung e a leitura é realizada com muito custo, demora um pouco, há algum ajuste que posso realizar no código para melhorar a efetividade da leitura?
CurtirCurtir
Olá Adriano, tudo bem ?
Você já testou com outro código, as vezes o problema pode ser a qualidade do código que você está utilizando.
Espero ter ajudado.
CurtirCurtir
Excelente Tutorial Juliano !!! Uma dúvida ! Gostaria de saber se tem como Customizar a ScanPage, tirando essa linha vermelha e colocando um quadrado com bordas na cor verde-limão . Existe essa possibilidade de Customizar o Zxing ?
CurtirCurtir
Obrigado 🙂
Sim… tem como. Porém, você tem que criar a sua view, para cada plataforma.
Para saber mais, acesse esse link e leia a sessão “Custom Overlays”
https://github.com/Redth/ZXing.Net.Mobile
CurtirCurtido por 1 pessoa
Olá, Juliano. Gostaria de implementar código de barras para um carteirinha virtual e gerar boleto, que estou fazendo em xamarin forms, pode me dar alguma dica.
CurtirCurtir
Para ler o código de barras, este exemplo do Scanner resolve o seu problema. Para gerar boletos, eu particularmente recomendaria realizar a geração do boleto do lado do servidor. Dê uma olhada no plugin BoletoNet. https://github.com/BoletoNet
CurtirCurtir
voce conhece algum exemplo?
CurtirCurtir
Sim.. este artigo serve também para códigos de barra. A parte do boleto não conheço nenhum até o momento.
CurtirCurtir