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));