Skip to content

Instantly share code, notes, and snippets.

@Clancey
Created April 6, 2016 19:01
Show Gist options
  • Save Clancey/fbf957844c6d98e755ec292e779cceec to your computer and use it in GitHub Desktop.
Save Clancey/fbf957844c6d98e755ec292e779cceec to your computer and use it in GitHub Desktop.
NGraphicsExtensions
using System;
using System.IO;
using UIKit;
namespace NGraphics
{
public static class NGraphicsExtensions
{
static readonly IPlatform Platform = new ApplePlatform();
static readonly double Scale = (double) UIScreen.MainScreen.Scale;
public static void LoadSvg(this UIImageView imageView, string svg)
{
var s = imageView.Bounds.Size;
LoadSvg(imageView, svg, new Size(s.Width, s.Height));
}
public static void LoadSvgFromResource(this UIImageView imageView, string resourceName,UIImageRenderingMode renderingMode = UIImageRenderingMode.Automatic)
{
var s = imageView.Bounds.Size;
var fileName = System.IO.Path.GetFileNameWithoutExtension(resourceName);
using (var stream = new StreamReader(ResourceLoader.GetEmbeddedResourceStream(resourceName))) {
var image = LoadImageFromSvg(fileName, stream, new Size(s.Width, s.Height), renderingMode);
imageView.Image = image;
}
}
public static void LoadSvg(this UIImageView imageView, string svg, Size size,
UIImageRenderingMode renderingMode = UIImageRenderingMode.Automatic)
{
var image = svg.LoadImageFromSvg(size, renderingMode);
imageView.Image = image;
}
public static UIImage LoadImageFromSvg(this string svg, Size size,
UIImageRenderingMode renderingMode = UIImageRenderingMode.Automatic)
{
var fileName = System.IO.Path.GetFileNameWithoutExtension(svg);
using (var file = File.OpenText(svg))
{
return LoadImageFromSvg(fileName, file, size, renderingMode);
}
}
public static UIImage LoadImageFromSvg(string fileName, TextReader file, Size size,
UIImageRenderingMode renderingMode = UIImageRenderingMode.Automatic)
{
try
{
var graphic = Graphic.LoadSvg(file);
//Shame on Size not being Equatable ;)
if (size.Width <= 0 || size.Height <= 0)
size = graphic.Size;
var gSize = graphic.Size;
if (gSize.Width > size.Width || size.Height > gSize.Height)
{
var ratioX = size.Width/gSize.Width;
var ratioY = size.Height/gSize.Height;
var ratio = Math.Min(ratioY, ratioX);
graphic.Size = size = new Size(gSize.Width*ratio, gSize.Height*ratio);
}
var c = Platform.CreateImageCanvas(size, Scale);
graphic.Draw(c);
var image = c.GetImage().GetUIImage();
if (renderingMode != UIImageRenderingMode.Automatic)
image = image.ImageWithRenderingMode(renderingMode);
image.AccessibilityIdentifier = fileName;
return image;
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Failed parsing: {0}", fileName);
// throw;
return null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment