2014-12-07 96 views
1

我正在使用ZXing.Net庫從相機掃描/讀取條形碼。我已經使用了下面的例子:Windows Phone 8.1:使用ZXing.Net從相機掃描條形碼

https://zxingnet.codeplex.com/SourceControl/latest#trunk/Clients/WindowsRTDemo/MainPage.xaml.cs

但它不工作。它凍結了設備。

如何在Windows Phone 8.1中使用ZXing.Net庫?任何示例?
是否有其他庫可用?

+1

嘗試使用F10找出在什麼線路設備凍結。 – 2014-12-07 10:08:32

+1

我建議你做Eldar說的話,看來這傢伙也有同樣的問題:http://zxingnet.codeplex.com/discussions/566782 – 2014-12-07 10:23:29

回答

1

首先,您需要添加Zxing.Net庫,並在您的前端

<phone:PhoneApplicationPage 
x:Class="BarCode.Scan" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
FontFamily="{StaticResource PhoneFontFamilyNormal}" 
FontSize="{StaticResource PhoneFontSizeNormal}" 
Foreground="{StaticResource PhoneForegroundBrush}" 
SupportedOrientations="Portrait" Orientation="Portrait" 
mc:Ignorable="d" 
shell:SystemTray.IsVisible="True"> 

<!--LayoutRoot is the root grid where all page content is placed--> 
<Grid x:Name="LayoutRoot" Background="Transparent"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="*" /> 

    </Grid.RowDefinitions> 

    <Canvas x:Name="viewfinderCanvas" Margin="0,0,0,10"> 

     <!--Camera viewfinder --> 
     <Canvas.Background> 

      <VideoBrush x:Name="viewfinderBrush"> 
       <VideoBrush.RelativeTransform> 
        <CompositeTransform 
        x:Name="viewfinderTransform" 
        CenterX="0.5" 
        CenterY="0.5" 
        Rotation="90"/> 
       </VideoBrush.RelativeTransform> 
      </VideoBrush> 
     </Canvas.Background> 
     <TextBlock 
     x:Name="focusBrackets" 
     Text="[ ]" 
     FontSize="40" Visibility="Collapsed"/> 
     <TextBlock Canvas.Left="129" TextWrapping="Wrap" Text="Tap to read the Barcode" Canvas.Top="721" Width="233" FontFamily="Segoe UI"/> 
    </Canvas> 
    <!--Used for debugging >--> 
    <!--<StackPanel Grid.Row="1" Margin="20, 0"> 
     <TextBlock x:Name="tbBarcodeType" FontWeight="ExtraBold" /> 
     <TextBlock x:Name="tbBarcodeData" FontWeight="ExtraBold" TextWrapping="Wrap" /> 
    </StackPanel>--> 
</Grid> 

而在後端使用使用這項

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Navigation; 
using Microsoft.Phone.Controls; 
using Microsoft.Phone.Shell; 
using Microsoft.Devices; 
using ZXing; 
using System.Windows.Threading; 
using System.Windows.Media.Imaging; 
using System.Windows.Input; 

namespace BarCode 
{ 
    public partial class Scan : PhoneApplicationPage 
    { 
     private PhotoCamera _phoneCamera; 
     private IBarcodeReader _barcodeReader; 
     private DispatcherTimer _scanTimer; 
     private WriteableBitmap _previewBuffer; 
     public Scan() 
     { 
      InitializeComponent(); 
     } 

     protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
     { 
      // Initialize the camera object 
      _phoneCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary); 
      // _phoneCamera.Initialized += cam_Initialized; 
      _phoneCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized); 
      _phoneCamera.AutoFocusCompleted += _phoneCamera_AutoFocusCompleted; 

      CameraButtons.ShutterKeyHalfPressed += CameraButtons_ShutterKeyHalfPressed; 

      //Display the camera feed in the UI 
      viewfinderBrush.SetSource(_phoneCamera); 


      // This timer will be used to scan the camera buffer every 250ms and scan for any barcodes 
      _scanTimer = new DispatcherTimer(); 
      _scanTimer.Interval = TimeSpan.FromMilliseconds(250); 
      _scanTimer.Tick += (o, arg) => ScanForBarcode(); 

      viewfinderCanvas.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(focus_Tapped); 

      base.OnNavigatedTo(e); 
     } 


     void _phoneCamera_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e) 
     { 
      Deployment.Current.Dispatcher.BeginInvoke(delegate() 
      { 
       focusBrackets.Visibility = Visibility.Collapsed; 
      }); 
     } 

     void focus_Tapped(object sender, System.Windows.Input.GestureEventArgs e) 
     { 
      try 
      { 
       if (_phoneCamera != null) 
       { 
        if (_phoneCamera.IsFocusAtPointSupported == true) 
        { 
         // Determine the location of the tap. 
         Point tapLocation = e.GetPosition(viewfinderCanvas); 

         // Position the focus brackets with the estimated offsets. 
         focusBrackets.SetValue(Canvas.LeftProperty, tapLocation.X - 30); 
         focusBrackets.SetValue(Canvas.TopProperty, tapLocation.Y - 28); 

         // Determine the focus point. 
         double focusXPercentage = tapLocation.X/viewfinderCanvas.ActualWidth; 
         double focusYPercentage = tapLocation.Y/viewfinderCanvas.ActualHeight; 

         // Show the focus brackets and focus at point. 
         focusBrackets.Visibility = Visibility.Visible; 
         _phoneCamera.FocusAtPoint(focusXPercentage, focusYPercentage); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       _phoneCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized); 
      } 
     } 


     void CameraButtons_ShutterKeyHalfPressed(object sender, EventArgs e) 
     { 
      _phoneCamera.Focus(); 
     } 


     protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e) 
     { 
      //we're navigating away from this page, we won't be scanning any barcodes 
      _scanTimer.Stop(); 

      if (_phoneCamera != null) 
      { 
       // Cleanup 
       _phoneCamera.Dispose(); 
       _phoneCamera.Initialized -= cam_Initialized; 
       CameraButtons.ShutterKeyHalfPressed -= CameraButtons_ShutterKeyHalfPressed; 
      } 
     } 

     void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e) 
     { 
      if (e.Succeeded) 
      { 
       this.Dispatcher.BeginInvoke(delegate() 
       { 
        _phoneCamera.FlashMode = FlashMode.Off; 
        _previewBuffer = new WriteableBitmap((int)_phoneCamera.PreviewResolution.Width, (int)_phoneCamera.PreviewResolution.Height); 

        _barcodeReader = new BarcodeReader(); 

        // By default, BarcodeReader will scan every supported barcode type 
        // If we want to limit the type of barcodes our app can read, 
        // we can do it by adding each format to this list object 

        //var supportedBarcodeFormats = new List<BarcodeFormat>(); 
        //supportedBarcodeFormats.Add(BarcodeFormat.QR_CODE); 
        //supportedBarcodeFormats.Add(BarcodeFormat.DATA_MATRIX); 
        //_bcReader.PossibleFormats = supportedBarcodeFormats; 

        _barcodeReader.TryHarder = true; 

        _barcodeReader.ResultFound += _bcReader_ResultFound; 
        _scanTimer.Start(); 
       }); 
      } 
      else 
      { 
       Dispatcher.BeginInvoke(() => 
       { 
        MessageBox.Show("Unable to initialize the camera"); 
       }); 
      } 
     } 

     void _bcReader_ResultFound(Result obj) 
     { 
      // If a new barcode is found, vibrate the device and display the barcode details in the UI 
      //if (!obj.Text.Equals(tbBarcodeData.Text)) 
      //{ 
       VibrateController.Default.Start(TimeSpan.FromMilliseconds(100)); 
       //tbBarcodeType.Text = obj.BarcodeFormat.ToString(); 
       //tbBarcodeData.Text = obj.Text; 
       //NavigationService.Navigate(new Uri(string.Format("/AddCustomer.xaml?parameter={0}", Uri.EscapeUriString(obj.Text), UriKind.Relative))); 
       PhoneApplicationService.Current.State["Text"] = obj.Text; 
      NavigationService.Navigate(new Uri("/PageYouWantToGetResult.xaml", UriKind.Relative)); 

     } 

     private void ScanForBarcode() 
     { 
      //grab a camera snapshot 
      _phoneCamera.GetPreviewBufferArgb32(_previewBuffer.Pixels); 
      _previewBuffer.Invalidate(); 

      //scan the captured snapshot for barcodes 
      //if a barcode is found, the ResultFound event will fire 
      _barcodeReader.Decode(_previewBuffer); 
     } 

     protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) 
     { 
      NavigationService.Navigate(new Uri("/PageYouWantToNavigate.xaml", UriKind.Relative)); 
      base.OnBackKeyPress(e); 

     } 
    } 
}