Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Created August 9, 2019 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/e24363f83b317e055530c32c9a7e48d6 to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/e24363f83b317e055530c32c9a7e48d6 to your computer and use it in GitHub Desktop.
Xamarin.Forms RadBarcode to Bitmap
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:telerikBarcode="clr-namespace:Telerik.XamarinForms.Barcode;assembly=Telerik.XamarinForms.Barcode"
x:Class="BarcodeCanvasToBitmap.Portable.MainPage">
<Grid>
<telerikBarcode:RadBarcode x:Name="barcode"
Value="https://www.telerik.com/xamarin-ui"
WidthRequest="100"
HeightRequest="100">
<telerikBarcode:RadBarcode.Symbology>
<telerikBarcode:QRCode SizingMode="Stretch" />
</telerikBarcode:RadBarcode.Symbology>
</telerikBarcode:RadBarcode>
<Button Text="Export As PNG"
HorizontalOptions="Center"
Margin="0,0,0,10"
VerticalOptions="End"
Clicked="Button_OnClicked" />
</Grid>
</ContentPage>
using System;
using System.IO;
using System.Linq;
using SkiaSharp;
using SkiaSharp.Views.Forms;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly:XamlCompilation(XamlCompilationOptions.Compile)]
namespace BarcodeCanvasToBitmap.Portable
{
public partial class MainPage : ContentPage
{
private SKPixmap pixmap;
public MainPage()
{
InitializeComponent();
// Get a reference to the SKCanvasView inside the RadBarcode
SKCanvasView canvasView = barcode.Children.FirstOrDefault(c => c.GetType() == typeof(SKCanvasView)) as SKCanvasView;
// subscribe to the PaintSurface event
if(canvasView != null)
{
canvasView.PaintSurface += CanvasView_PaintSurface;
}
}
private async void Button_OnClicked(object sender, EventArgs e)
{
// Choose the format you want the image in
var chosenImageFormat = SKEncodedImageFormat.Png;
// Use SKManagedStream, this will prevent you from needing pointers!
using (MemoryStream ms = new MemoryStream())
using (SKManagedWStream ws = new SKManagedWStream(ms))
{
// Get the image from the pixel map, encoded as your chosen image file format
pixmap.Encode(ws, chosenImageFormat, 90);
// Get the byte array from the stream
byte[] encodedImageBytes = ms.ToArray();
// Save the byte array to a file. this example saves it to the platform's app local folder
// Install "CommonHelpers" NuGet package to class library project
await CommonHelpers.Extensions.FileExtensions.SaveToLocalFolderAsync(encodedImageBytes, $"Barcode.{chosenImageFormat}");
}
}
private void CanvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
// after the canvas is painted, you can get a pixel map
this.pixmap = e.Surface.PeekPixels();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment