public static BitmapInfo LoadBitmap(object bitmapStream) { if (bitmapStream is Stream stream) { byte[] buffer = new byte[4]; stream.Position = 0; stream.Read(buffer, 0, 4); stream.Position = 0; if (System.Text.Encoding.UTF8.GetString(buffer, 0, 4).ToLower().Equals("<svg")) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); return(new BitmapInfo { Svg = svg }); } var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes())); return(new BitmapInfo { Bitmap = image }); } if (bitmapStream is Sprite sprite) { return(new BitmapInfo { Sprite = sprite }); } return(null); }
/// <summary> /// Creates the image. /// </summary> /// <returns>The image.</returns> /// <param name="stream">Stream.</param> /// <param name="width">Width.</param> /// <param name="height">Height.</param> /// <param name="color">Color.</param> public static Task <Stream> CreateImage(Stream stream, double width, double height, Color color) { var screenScale = SvgImageSource.ScreenScale; var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); var size = CalcSize(svg.Picture.CullRect.Size, width, height); var scale = CalcScale(svg.Picture.CullRect.Size, size, screenScale); var matrix = SKMatrix.MakeScale(scale.Item1, scale.Item2); using (var bitmap = new SKBitmap((int)(size.Width * screenScale), (int)(size.Height * screenScale))) using (var canvas = new SKCanvas(bitmap)) using (var paint = new SKPaint()) { if (!color.IsDefault) { paint.ColorFilter = SKColorFilter.CreateBlendMode(ToSKColor(color), SKBlendMode.SrcIn); } canvas.Clear(SKColors.Transparent); // very very important! canvas.DrawPicture(svg.Picture, ref matrix, paint); using (var image = SKImage.FromBitmap(bitmap)) using (var encoded = image.Encode()) { var imageStream = new MemoryStream(); encoded.SaveTo(imageStream); imageStream.Position = 0; return(Task.FromResult(imageStream as Stream)); } } }
public SvgButton(string DefaultFile, string TouchedFile, SKMatrix Scale, Context context) { var assets = context.Assets; SvgTouched = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(TouchedFile))) { SvgTouched.Load(stream.BaseStream); } // SvgTouched.Load(TouchedFile); SvgDefault = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(DefaultFile))) { SvgDefault.Load(stream.BaseStream); } // SvgDefault.Load(DefaultFile); scale = Scale; /* #TODO * if (UIScreen.MainScreen.Scale > 2) * { * scale = SKMatrix.MakeScale(Scale.ScaleX * 1.5f, Scale.ScaleY * 1.5f); * } * else * { * scale = Scale; * } */ }
F9PImageData(SkiaSharp.Extended.Svg.SKSvg skSvg, string key) { _width = skSvg.CanvasSize.Width; _height = skSvg.CanvasSize.Height; SKSvg = skSvg; Key = key; }
public static void RenderSvg(SKCanvas canvas, SkiaSharp.Extended.Svg.SKSvg svg, float x, float y, float orientation = 0, float offsetX = 0, float offsetY = 0, LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left, LabelStyle.VerticalAlignmentEnum verticalAlignment = LabelStyle.VerticalAlignmentEnum.Top, float opacity = 1f, float scale = 1f) { canvas.Save(); canvas.Translate(x, y); canvas.RotateDegrees(orientation, 0, 0); // todo: degrees or radians? canvas.Scale(scale, scale); var halfWidth = svg.CanvasSize.Width / 2; var halfHeight = svg.CanvasSize.Height / 2; // 0/0 are assumed at center of image, but Svg has 0/0 at left top position canvas.Translate(-halfWidth + offsetX, -halfHeight - offsetY); var rect = new SKRect(-halfWidth, -halfHeight, +halfWidth, +halfHeight); //var color = new SKColor(255, 255, 255, (byte)(255 * opacity)); //var paint = new SKPaint { Color = color, FilterQuality = SKFilterQuality.High }; canvas.DrawPicture(svg.Picture); canvas.Restore(); }
private void Svg2Png(PlotModel model) { SvgExporter exporter = new SvgExporter { Width = 600, Height = 400 }; var svg = new SkiaSharp.Extended.Svg.SKSvg(); var imgQuality = 80; using (FileStream fs = System.IO.File.Create("temp.svg")) { exporter.Export(model, fs); } using (FileStream png = System.IO.File.Create("img.png")) { var pict = svg.Load("temp.svg"); var dimen = new SKSizeI( (int)Math.Ceiling(pict.CullRect.Width), (int)Math.Ceiling(pict.CullRect.Height) ); var matrix = SKMatrix.MakeScale(1, 1); var img = SKImage.FromPicture(pict, dimen, matrix); // convert to PNG var skdata = img.Encode(SKEncodedImageFormat.Png, imgQuality); skdata.SaveTo(png); } }
public ImageSource ProvideValue(IServiceProvider serviceProvider) { if (string.IsNullOrEmpty(ResourceName)) { return(null); } if (!imagedataDictionary.TryGetValue(ResourceName, out var imagedata)) { var assembly = GetType().GetTypeInfo().Assembly; var assemblyName = assembly.GetName().Name; var skSvg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(Width, Height)); skSvg.Load(assembly.GetManifestResourceStream(assemblyName + "." + ResourceName)); var bitmap = new SKBitmap(Width, Height); var canvas = new SKCanvas(bitmap); canvas.Clear(SKColors.Transparent); canvas.DrawPicture(skSvg.Picture); canvas.Flush(); canvas.Save(); imagedata = SKImage.FromBitmap(bitmap).ToRasterImage().Encode(SKEncodedImageFormat.Png, 100); imagedataDictionary.Add(ResourceName, imagedata); } return(ImageSource.FromStream(() => imagedata.AsStream())); }
/// <summary> /// Load SVG image from resources /// </summary> public static SkiaSharp.Extended.Svg.SKSvg GetSvgImage(string assemblyName, string resourceKey) { SkiaSharp.Extended.Svg.SKSvg svg = null; string resourceId = assemblyName + "." + resourceKey; if (!SvgImage.SvgCache.TryGetValue(resourceId, out svg)) { Assembly assembly = Assembly.Load(new AssemblyName(assemblyName)); using (Stream stream = assembly.GetManifestResourceStream(resourceId)) { if (stream == null) { throw new FileNotFoundException($"SvgIcon : could not load SVG file {resourceId} in assembly {assembly}. Make sure the ID is correct, the file is there and it is set to Embedded Resource build action."); } svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SvgImage.SvgCache.Add(resourceId, svg); } } return(svg); }
static public F9PImageData Create(System.IO.Stream stream, string key) { // necessary if we can't random access the stream - which should be the case with url streams using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); //TODO: Try opening SVG with SKBitmap.Decode. Could be viable alternative to the following? using (var sr = new StreamReader(memoryStream)) { if (IsSvg(sr)) { var skSvg = new SkiaSharp.Extended.Svg.SKSvg(); skSvg.Load(memoryStream); return(new F9PImageData(skSvg, key)); } var skBitmap = SKBitmap.Decode(memoryStream); if (skBitmap != null) { return(new F9PImageData(skBitmap, key)); } } } return(null); }
/// <summary> /// Paint svg image /// </summary> protected override void OnPaintSurface(SKPaintSurfaceEventArgs e) { base.OnPaintSurface(e); e.Surface.Canvas.Clear(); if (string.IsNullOrEmpty(ResourceKey) || string.IsNullOrEmpty(AssemblyName)) { return; } // Get device pixel intencity scale DeviceScale = (float)(e.Info.Width / Width); if (m_svg == null) { m_svg = GetSvgImage(AssemblyName, ResourceKey); } SKPoint position = CalculateTranslation(e.Info); float scale = CalculateScale(m_svg.Picture.CullRect.Size, WidthRequest, HeightRequest) * DeviceScale; SKMatrix matrix = new SKMatrix(); matrix.SetScaleTranslate(scale, scale, position.X, position.Y); using (var paint = new SKPaint()) { // paint.ColorFilter = SKColorFilter.CreateBlendMode(Color.ToSKColor(), SKBlendMode.SrcIn); paint.Style = SKPaintStyle.Fill; paint.IsAntialias = true; paint.FilterQuality = SKFilterQuality.None; e.Surface.Canvas.DrawPicture(m_svg.Picture, ref matrix, paint); } }
public static SkiaSharp.Extended.Svg.SKSvg GetCache(string imageName) { if (string.IsNullOrEmpty(imageName)) { return(null); } if (!SvgImage.SvgCache.TryGetValue(imageName, out var svg)) { var assemply = typeof(SKScrollView).Assembly; var keyName = $"{assemply.GetName().Name}.Assets.{imageName}.svg"; using (var stream = assemply.GetManifestResourceStream(keyName)) { if (stream != null) { svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SvgImage.SvgCache[imageName] = svg; } else { SvgImage.SvgCache[imageName] = null; } } } return(svg); }
public static void Draw(SKCanvas canvas, SkiaSharp.Extended.Svg.SKSvg svg, float x, float y, float orientation = 0, float offsetX = 0, float offsetY = 0, LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left, LabelStyle.VerticalAlignmentEnum verticalAlignment = LabelStyle.VerticalAlignmentEnum.Top, float opacity = 1f, float scale = 1f) { // todo: I assume we also need to apply opacity. // todo: It seems horizontalAlignment and verticalAlignment would make sense too. Is this similar to Anchor? canvas.Save(); canvas.Translate(x, y); canvas.RotateDegrees(orientation, 0, 0); // todo: degrees or radians? canvas.Scale(scale, scale); var halfWidth = svg.CanvasSize.Width / 2; var halfHeight = svg.CanvasSize.Height / 2; // 0/0 are assumed at center of image, but Svg has 0/0 at left top position canvas.Translate(-halfWidth + offsetX, -halfHeight - offsetY); canvas.DrawPicture(svg.Picture, new SKPaint() { IsAntialias = true }); canvas.Restore(); }
public SvgButton(string DefaultFile, string TouchedFile, SKMatrix Scale) { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(UIPhotoTakerView)).Assembly; SvgTouched = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + TouchedFile))) { SvgTouched.Load(stream.BaseStream); } SvgDefault = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + DefaultFile))) { SvgDefault.Load(stream.BaseStream); } if (UIScreen.MainScreen.Scale > 2) { scale = SKMatrix.MakeScale(Scale.ScaleX * 1.5f, Scale.ScaleY * 1.5f); } else { scale = Scale; } }
protected override Task OnInit() { svg = new SKSvg(); using (var stream = SampleMedia.Images.OpacitySvg) svg.Load(stream); return(base.OnInit()); }
private SkiaSharp.Extended.Svg.SKSvg CreateSKSvg() { var stream = GetEmbeddedResourceStream(); var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); return(svg); }
public void EnsurePicture_AlreadyResolved() { SvgView view = new SvgView(); SKSvg skSvg = new SKSvg(); view.SetMemberValue("_skSvg", skSvg); view.CallPrivateMethod("EnsurePicture"); Assert.AreEqual(skSvg, view.GetMemberValue <SKSvg>("_skSvg")); }
private void LoadSvg(string svgName) { // create a new SVG object svg = new SkiaSharp.Extended.Svg.SKSvg(); // load the SVG document from a stream using (var stream = GetImageStream(svgName)) svg.Load(stream); }
F9PImageData(SkiaSharp.Extended.Svg.SKSvg skSvg, string key) { P42.Utils.DebugExtensions.AddToCensus(this); _width = skSvg.CanvasSize.Width; _height = skSvg.CanvasSize.Height; SKSvg = skSvg; Key = key; }
/// <summary> /// Назначить из Assets\svg SVG-картинку на ImageView /// </summary> /// <param name="imgView"></param> /// <param name="fileName"></param> /// <param name="wantedWidth"></param> /// <param name="wantedHeight"></param> /// <param name="preprocess"></param> public static void AssignSvg([NotNull] ImageView imgView, string fileName, Action <XmlDocument> preprocess, int?wantedWidth = null, int?wantedHeight = null) { if (wantedWidth == null) { wantedWidth = imgView.Width; } if (wantedHeight == null) { wantedHeight = imgView.Height; } const int bestQuality = 100; var parentColor = TryGetBackgroundColor(imgView); var viewActivity = (Activity)imgView.Context; using (var reader = new StreamReader(viewActivity.Assets.Open(Path.Combine("svg", Path.ChangeExtension(fileName, "svg").AssertNull())))) { var xmlDoc = new XmlDocument(); xmlDoc.Load(reader); xmlDoc.DocumentElement.VoidAssertNull(); xmlDoc.DocumentElement.SetAttribute("width", wantedWidth.ToString()); xmlDoc.DocumentElement.SetAttribute("height", wantedHeight.ToString()); preprocess?.Invoke(xmlDoc); if (parentColor.HasValue) { var bkColorRect = xmlDoc.CreateElement("rect"); bkColorRect.SetAttribute("style", $"fill: {parentColor.Value.ToHtmlValue()}"); bkColorRect.SetAttribute("x", "0"); bkColorRect.SetAttribute("y", "0"); bkColorRect.SetAttribute("width", wantedWidth.ToString()); bkColorRect.SetAttribute("height", wantedHeight.ToString()); xmlDoc.DocumentElement.AssertNull().InsertAfter(bkColorRect, null); } using (var alterStream = new MemoryStream()) { xmlDoc.Save(alterStream); alterStream.Seek(0, SeekOrigin.Begin); var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(wantedWidth.Value, wantedHeight.Value)); svg.Load(alterStream); using (var svgBitmap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height)) { using (var canvas = new SKCanvas(svgBitmap)) { canvas.DrawPicture(svg.Picture); canvas.Flush(); canvas.Save(); } using (var image = SKImage.FromBitmap(svgBitmap)) using (var data = image.Encode(SKEncodedImageFormat.Png, bestQuality)) { var bmpArray = data.ToArray(); imgView.SetImageBitmap(BitmapFactory.DecodeByteArray(bmpArray, 0, bmpArray.Length)); } } } } }
void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e) { if (string.IsNullOrEmpty(Source)) { return; } if (Clicked == null && !AddPadding) { _padding = 0; } try { if (_fileContent == null) { _fileContent = Source.GetFileContents(); } if (Clicked == null) { _padding = 0; } var svg = new SkiaSharp.Extended.Svg.SKSvg(); var bytes = System.Text.Encoding.UTF8.GetBytes(_fileContent); var stream = new MemoryStream(bytes); svg.Load(stream); var canvas = e.Surface.Canvas; using (var paint = new SKPaint()) { if (Color != Color.Lime) { //Set the paint color paint.ColorFilter = SKColorFilter.CreateBlendMode(Color.ToSKColor(), SKBlendMode.SrcIn); } int multiplier = (int)(e.Info.Width / WidthRequest); //Scale up the SVG image to fill the canvas float canvasMin = Math.Min(e.Info.Width - _padding * 2 * multiplier, e.Info.Height - _padding * 2 * multiplier); float svgMax = Math.Max(svg.Picture.CullRect.Width, svg.Picture.CullRect.Height); float scale = canvasMin / svgMax; var matrix = SKMatrix.MakeScale(scale, scale); matrix.TransX = _padding * multiplier; matrix.TransY = _padding * multiplier; canvas.Clear(Color.Transparent.ToSKColor()); canvas.DrawPicture(svg.Picture, ref matrix, paint); } } catch (Exception ex) { Log.Instance.WriteLine($"Error drawing SvgImage w/ ImagePath {Source}: {ex}"); } }
private SKPicture LoadScene() { var svg = new SkiaSharp.Extended.Svg.SKSvg(); var fileName = $"SkiaScene.NativeSample.{_fileName}"; var assembly = typeof(SvgSceneRenderer).GetTypeInfo().Assembly; var stream = assembly.GetManifestResourceStream(fileName); var result = svg.Load(stream); return(result); }
public SvgButton(string DefaultFile, string ToggledFile, string TouchedFile, SKMatrix Scale) : this(DefaultFile, TouchedFile, Scale) { var assembly = IntrospectionExtensions.GetTypeInfo(typeof(UIPhotoTakerView)).Assembly; SvgToggled = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assembly.GetManifestResourceStream(RESOURCE_PREFIX + ToggledFile))) { SvgToggled.Load(stream.BaseStream); } }
public SvgButton(string DefaultFile, string ToggledFile, string TouchedFile, SKMatrix Scale, Context Context) : this(DefaultFile, TouchedFile, Scale, Context) { var assets = Context.Assets; SvgToggled = new SkiaSharp.Extended.Svg.SKSvg(190f); using (var stream = new StreamReader(assets.Open(ToggledFile))) { SvgToggled.Load(stream.BaseStream); } }
internal static SKPicture SvgToSKPicture(string xml) { if (!string.IsNullOrEmpty(xml)) { using (var stream = new StringReader(xml)) using (var reader = XmlReader.Create(stream)) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); return(svg.Load(reader)); } } return(null); }
private void Load(string[] fileNames, string pathToFull, SegmentType type, SegmentWeight weight) { for (var i = 0; i < fileNames.Length; i++) { var svg = new SKSvg(); svg.Load(_assembly.GetManifestResourceStream(fileNames[i])); _svgs[type][weight].Add(i, svg); } var full = new SKSvg(); full.Load(_assembly.GetManifestResourceStream(pathToFull)); _svgs[type][weight].Add(FullSegment, full); Loaded[type][weight].OnNext(Unit.Default); Loaded[type][weight] = new BehaviorSubject <Unit>(Unit.Default); }
protected override void OnPropertyChanged(string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName == ResourceIdProperty.PropertyName || propertyName == HorizontalAligmentProperty.PropertyName || propertyName == VerticalAligmentProperty.PropertyName || propertyName == StretchProperty.PropertyName) { if (propertyName == ResourceIdProperty.PropertyName) { _skSvg = null; } InvalidateSurface(); } }
public static void LoadAsXMLdocument <T>(this SKSvg svg, string svgNamePath, Action <XmlDocument> actionXmlDoc = null) { var assembly = typeof(T).Assembly; using (var stream = assembly.GetManifestResourceStream(svgNamePath)) { var document = new XmlDocument(); using (var reader = XmlReader.Create(stream)) { document.Load(reader); } actionXmlDoc?.Invoke(document); svg.Load(document.XmlDocumentToStream()); } }
/// <summary> /// Add submenu icon /// </summary> protected override void OnPaintForeground(SKPaintSurfaceEventArgs e, Rectangle availableSpace) { Size actualSubMenuIconSize = new Size(); if (ItemsSource != null && ItemsSource.Count > 0 && IsSubMenuIconVisible && string.IsNullOrEmpty(SubMenuIconAssemblyName) == false && string.IsNullOrEmpty(SubMenuIconResourceKey) == false) { if (m_subMenuIconSvg == null) { m_subMenuIconSvg = SvgImage.GetSvgImage(SubMenuIconAssemblyName, SubMenuIconResourceKey); } Rectangle subMenuIconActualLocation = new Rectangle( availableSpace.Width - _subMenuIconSize.Width - SubMenuIconMargin.Right, (availableSpace.Height - _subMenuIconSize.Height) / 2, _subMenuIconSize.Height, _subMenuIconSize.Width); float skSubMenuIconX = (float)subMenuIconActualLocation.X * DeviceScale; float skSubMenuIconY = (float)subMenuIconActualLocation.Y * DeviceScale; SKMatrix subMenuIconMatrix = new SKMatrix(); SKPoint subMenuIconPosition = new SKPoint(); float scale = SvgImage.CalculateScale(m_subMenuIconSvg.Picture.CullRect.Size, SubMenuIconWidthRequest, SubMenuIconHeightRequest) * DeviceScale; subMenuIconPosition.X = (float)skSubMenuIconX + (float)((SubMenuIconWidthRequest - _subMenuIconSize.Width) / 2) * DeviceScale; subMenuIconPosition.Y = (float)skSubMenuIconY + (float)((SubMenuIconHeightRequest - _subMenuIconSize.Height) / 2) * DeviceScale; subMenuIconMatrix.SetScaleTranslate(scale, scale, subMenuIconPosition.X, subMenuIconPosition.Y); using (var paint = new SKPaint()) { Color color = GetActualSubMenuIconColor(); paint.ColorFilter = SKColorFilter.CreateBlendMode(color.ToSKColor(), SKBlendMode.SrcIn); paint.Style = SKPaintStyle.Fill; paint.IsAntialias = true; e.Surface.Canvas.DrawPicture(m_subMenuIconSvg.Picture, ref subMenuIconMatrix, paint); } actualSubMenuIconSize = _subMenuIconSize; } base.OnPaintForeground(e, new Rectangle(availableSpace.X + _checkBoxSize.Width, availableSpace.Y, availableSpace.Width - actualSubMenuIconSize.Width - _checkBoxSize.Width, availableSpace.Height)); }
/// <summary> /// The Plan constructor loads the plan from file and figures out its width and height. /// It also saves various variables which are needed later for displaying the plan. /// The parent constructor is called with the canvasView. canvasView is not required in /// this derived class. /// </summary> /// <param name="activity"></param> /// <param name="canvasView"></param> /// <param name="planPathName"></param> internal SVGPlan(AppCompatActivity activity, SKCanvasView canvasView, string planPathName) : base(activity, canvasView) { #if STOPWATCH Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); #endif // Create the SVG resource SVGCanvas = new SkiaSharp.Extended.Svg.SKSvg(); // Check if SVG file exists. This should already have been done before getting here, but just in case... Java.IO.File planFile = new Java.IO.File(planPathName); if (planFile.Exists()) { // Load the plan planSKPicture = loadPlan(planPathName); if (planSKPicture != null) { drawingWidth = planSKPicture.CullRect.Width; drawingHeight = planSKPicture.CullRect.Height; LogFile.WriteInfo(System.String.Format("planSKPicture size: {0} x {1}", drawingWidth, drawingHeight)); #if STOPWATCH stopwatch.Stop(); LogFile.WriteInfo(System.String.Format("Path.LoadPlan(): {0}ms", stopwatch.ElapsedMilliseconds)); stopwatch.Restart(); #endif } // if planSKPicture!=null else { // Do nothing. LoadPlan() throws an exception if plan can't be loaded. drawingWidth = 0; drawingHeight = 0; } #if STOPWATCH stopwatch.Stop(); LogFile.WriteInfo(System.String.Format("Plan() - completion: {0}ms", stopwatch.ElapsedMilliseconds)); #endif } // if (file.exists) else { String errorString = "File " + planPathName + " does not exist. "; LogFile.WriteError(errorString); throw new FileNotFoundException(errorString); } } // SVGPlan constructor
public static async Task GeneratePng(int width, int height, string filepath, string filename, int quality) { var svg2 = new SKSvg(new SKSize(width, height)); svg2.Load(filepath); using (var image = SKImage.FromPicture(svg2.Picture, new SKSizeI(width, height))) { using (var data = image.Encode(SKEncodedImageFormat.Png, quality)) { // save the data to a stream using (var stream = File.OpenWrite(filename)) { data.SaveTo(stream); await stream.FlushAsync(); } } } }