2017年8月19日 星期六

for xamarin 如何繪製一二維條碼

二維的比較簡單,先講二維的好了
不用ZXing,直接用CG--CoreGraphic套件就可以了
============================================
            /*
            Correction level option as below:
            L, // Level L (Low) 7% of codewords can be restored.
    M, // Level M (Medium) 15% of codewords can be restored.
           Q, // Level Q (Quartile) 25% of codewords can be restored.
            H // Level H (High) 30% of codewords can be restored.          
             */
            CoreImage.CIQRCodeGenerator ciQrCodeGen = new CoreImage.CIQRCodeGenerator() {
                Message = NSData.FromString("這裡面可以裝下1700多個漢字,請好好發揮了"),
                CorrectionLevel = "L",
            };
            var context = CoreImage.CIContext.FromOptions(null);
            //假設有個UIImageView叫imgQrCode,放置二維條碼
            imgQrCode.Image=UIImage.FromImage(
                context.CreateCGImage(ciQrCodeGen.OutputImage,ciQrCodeGen.OutputImage.Extent)
            );
============================================

相形之下,一維比較麻煩(以39碼為例):
---------------------------step1:-------------------------------------------------------
public interface IBarcodeService {
        Stream ConvertImageStream(string text, int width = 300, int height = 130);
    }
---------------------------step2:-------------------------------------------------------
class BarcodeService : IBarcodeService {
        public Stream ConvertImageStream(string text, int width = 300, int height = 130) {
            var barcodeWriter = new ZXing.Mobile.BarcodeWriter {
                Format = ZXing.BarcodeFormat.CODE_39,
                Options = new ZXing.Common.EncodingOptions {
                    Width = width,
                    Height = height,
                    Margin = 10
                }
            };
            barcodeWriter.Renderer = new ZXing.Mobile.BitmapRenderer();
            var bitmap = barcodeWriter.Write(text);
            var stream = bitmap.AsPNG().AsStream(); // this is the difference
            stream.Position = 0;

            return stream;
        }
---------------------------step3:-------------------------------------------------------
//假設我們要把一維條碼繪在UIImageView "imgCode39"上面...
var stream =new  Barcode.BarcodeService().ConvertImageStream("10607UP197419461A5B");
 imgCode39.Image= UIImage.LoadFromData(Foundation.NSData.FromStream(stream));


參考:https://forums.xamarin.com/discussion/28161/barcode-rendering-with-zxing-net-in-my-xamarin-forms-app

 大家加油了

沒有留言:

張貼留言