1. 程式人生 > >xamarin android 實現二維碼帶logo生成效果

xamarin android 實現二維碼帶logo生成效果

            MultiFormatWriter writer = new MultiFormatWriter();
            Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
            hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
            hint.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
            BarcodeWriter barcodeWriter 
= new BarcodeWriter(); var bm = writer.encode("123123123", BarcodeFormat.QR_CODE, 700, 700, hint); var bmp = barcodeWriter.Write(bm); //獲取二維碼實際尺寸(去掉二維碼兩邊空白後的實際尺寸) int[] rectangle = bm.getEnclosingRectangle(); Bitmap logo = BitmapFactory.DecodeResource(this
.Resources, Resource.Mipmap.timg); //計算插入圖片的大小和位置 int width = Math.Min((int)(rectangle[2] / 3.5), logo.Width); int height = Math.Min((int)(rectangle[3] / 3.5), logo.Height); int left = (bmp.Width - width) / 2; int top = (bmp.Height - height) / 2
; int right = left + width; int bottom = top + height; //將img轉換成bmp格式,否則後面無法建立Graphics物件 using (Android.Graphics.Canvas g = new Canvas(bmp)) { //先填充個白色背景 // g.DrawRect(new Rect(left-1, top-1, right+1, bottom+1), new Paint() { Color = Color.White }); g.DrawBitmap(logo, new Rect(0, 0, logo.Width, logo.Height), new Rect(left, top, right, bottom), new Paint()); } ImageView view = new ImageView(this); view.SetImageBitmap(bmp); this.AddContentView(view, new Android.Views.ViewGroup.LayoutParams(700, 700));