I am trying to load and render an image using the skia graphics library in my xamarin forms solution. When I try to render the image (running the android project) I get the following error:
Value cannot be null. Parameter name: codec
here is the code:
void OnPainting(object sender, SKPaintSurfaceEventArgs e)
{
var surface = e.Surface;
var canvas = surface.Canvas;
canvas.Clear(SKColors.White);
var filename = "test.jpg";
using (var stream = new SKFileStream(filename))
using (var bitmap = SKBitmap.Decode(stream)) // the error occurs on this line
using (var paint = new SKPaint())
{
canvas.DrawBitmap(bitmap, SKRect.Create(200, 200), paint);
}
}
I cannot find any sample code online for xamarin. Any sample code or links would be much appreciated.
thanks in advance
Value cannot be null. Parameter name: codec
I think it is possible you get a null object here: using (var stream = new SKFileStream(filename))
. I tried to created a demo, and it works fine.
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:skiaviews="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
x:Class="FormsIssue6.Page1">
<Grid>
<skiaviews:SKCanvasView x:Name="mycanvas" PaintSurface="OnPainting" />
</Grid>
</ContentPage>
Code behind:
private void OnPainting(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
var surface = e.Surface;
var canvas = surface.Canvas;
var assembly = typeof(Page1).GetTypeInfo().Assembly;
var fileStream = assembly.GetManifestResourceStream("YOUR-FILE-FULL-NAME");
// clear the canvas / fill with white
canvas.DrawColor(SKColors.White);
// decode the bitmap from the stream
using (var stream = new SKManagedStream(fileStream))
using (var bitmap = SKBitmap.Decode(stream))
using (var paint = new SKPaint())
{
// create the image filter
using (var filter = SKImageFilter.CreateBlur(5, 5))
{
paint.ImageFilter = filter;
// draw the bitmap through the filter
canvas.DrawBitmap(bitmap, SKRect.Create(640, 480), paint);
}
}
}
The file name in the code above should be like "YOUR PROJECT NAMESPACE"."File NAME", and this file is placed in PCL and build action of this file must be "Embedded Resource". For more information about working with file, you can refer to Files.
I cannot find any sample code online for xamarin. Any sample code or links would be much appreciated.
The package itself on Github has a code sample for Xamarin.Forms, you can refer to FormsSample.