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, null); canvas.Restore(); }
private static SkiaSharp.Extended.Svg.SKSvg LoadSVG(string key) { Assembly assembly = null; foreach (KeyValuePair <Assembly, List <string> > entry in ManifestResourceNames) { if (entry.Value.Contains(key)) { assembly = entry.Key; break; } } if (assembly == null) { throw new Exception($"Failed to locate assembly for resource {key}"); } // If not found in cache, load if (!SvgCache.TryGetValue(key, out SkiaSharp.Extended.Svg.SKSvg svg)) { using (Stream stream = assembly.GetManifestResourceStream(key)) { svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(stream); SvgCache.Add(key, svg); } } return(svg); }
private void OnSvgResourceKeyChanged(string oldValue, string newValue) { //"XApp.Views.Icons.ZWave.svg" picture = null; if (!string.IsNullOrEmpty(newValue)) { string resxId = newValue.IndexOf(".") > 0 ? newValue : $"{typeof(SvgIcon).Namespace}.Svg.{newValue}.svg"; if (!svgs.TryGetValue(resxId, out picture)) { using (Stream stream = GetType().Assembly.GetManifestResourceStream(resxId)) { if (stream != null) { Svg.SKSvg svg = new Svg.SKSvg(); svg.Load(stream); picture = svgs[resxId] = svg.Picture; } } } } InvalidateSurface(); }
private void SaveVector(Shape shape) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(shape.OutputPath); var svgRect = svg.Picture.CullRect; var(w, h) = CalculateResized((int)svgRect.Width, (int)svgRect.Height); float svgMax = Math.Max(w, h); float scale = w / svgRect.Width; var matrixS = SKMatrix.MakeScale(scale, scale); var matrixT = SKMatrix.MakeTranslation((MAX_SIZE - w) / 2, (MAX_SIZE - h) / 2); var matrix = SKMatrix.MakeIdentity(); SKMatrix.Concat(ref matrix, matrixT, matrixS); var target = new SKBitmap(MAX_SIZE, MAX_SIZE, SKImageInfo.PlatformColorType, SKAlphaType.Premul); using (target) using (var canvas = new SKCanvas(target)) { canvas.Clear(); canvas.DrawPicture(svg.Picture, ref matrix, _skPaint); SaveToFile(shape.Id, "svg", target); } }
public SKSvg Load(string svgImage) { try { var svg = new SkiaSharp.Extended.Svg.SKSvg(); Stream asset = null; try { asset = Application.Context.Assets.Open(svgImage); } catch (Exception) { throw new Exception($"SVG-file, {svgImage} cannot be foundin the Asset folder."); } svg.Load(asset); return(svg); } catch (Exception) { throw new Exception($"SVG-file, {svgImage} is not supported by SkiaSharp.Svg."); } }
public SKSvg Load(string svgImage) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(svgImage); return(svg); }
private static void CalculateBounds(bool forDrawing, SkiaSharp.Extended.Svg.SKSvg svg, Aspect aspect, double maxWidth, double maxHeight, out SKMatrix drawMatrix, out SKSizeI pixelSize) { // Determine bounds of SVG SKRect svgBounds = svg.ViewBox; if (svgBounds.Width == 0 || svgBounds.Height == 0) { svgBounds = new SKRect(0, 0, svg.CanvasSize.Width, svg.CanvasSize.Height); } // Unable to scale? double scaleX, scaleY; if (svgBounds.Width == 0 || svgBounds.Height == 0 || double.IsInfinity(maxWidth) || double.IsInfinity(maxHeight)) { scaleX = scaleY = 1; } else { // Scale properly double ratioX = maxWidth / svgBounds.Width, ratioY = maxHeight / svgBounds.Height; switch (aspect) { case Aspect.AspectFill: scaleX = scaleY = Math.Max(ratioX, ratioY); break; case Aspect.AspectFit: scaleX = scaleY = Math.Min(ratioX, ratioY); break; case Aspect.Fill: default: scaleX = ratioX; scaleY = ratioY; break; } } // Increase sizing for drawing if (forDrawing) { scaleX *= DemoUtilities.DisplayDensity; scaleY *= DemoUtilities.DisplayDensity; } // Apply scaling if (svg.ViewBox.Width != 0 && svg.ViewBox.Height != 0) { drawMatrix = SKMatrix.MakeTranslation(-svg.ViewBox.Left, -svg.ViewBox.Top); } else { drawMatrix = SKMatrix.MakeIdentity(); } SKMatrix.PreConcat(ref drawMatrix, SKMatrix.MakeScale((float)scaleX, (float)scaleY)); pixelSize = new SKSizeI((int)Math.Ceiling(scaleX * svgBounds.Width), (int)Math.Ceiling(scaleY * svgBounds.Height)); }
public SVGImaggeButton() : base() { svgLoaded = false; svgLoading = false; isDisposing = false; svg = new SVG.SKSvg(); previousColor = new SKColor(); previousBounds = new Rectangle(); bitmap = new SKBitmap(); canvas = new SKCanvas(bitmap); scale = SKMatrix.MakeScale(1, 1); this.MeasureInvalidated += OnMeasureInvalidated; }
}; // Only for high/med/low quality resizing of tiles public static BitmapInfo LoadBitmap(Stream bitmapStream, bool isSvg = false) { bitmapStream.Position = 0; if (isSvg) { var svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(bitmapStream); return(new BitmapInfo { Svg = svg }); } var image = SKImage.FromEncodedData(SKData.CreateCopy(bitmapStream.ToBytes())); return(new BitmapInfo { Bitmap = image }); }
public static SKBitmapImageSource Load(string source, Aspect aspect, double width, double height) { // No image needed? if (string.IsNullOrWhiteSpace(source) || width <= 0 || height <= 0) { return(null); } // Read the image string key = GetKey(source); SkiaSharp.Extended.Svg.SKSvg svg = LoadSVG(key); CalculateBounds(true, svg, aspect, width, height, out SKMatrix drawMatrix, out SKSizeI pixelSize); // Check the cache if (ImageSourceCache.TryGetValue(key, out Tuple <SKSizeI, SKBitmapImageSource> cacheEntry)) { if (cacheEntry.Item1.Width >= pixelSize.Width * (1 - CacheTolerance) && cacheEntry.Item1.Height >= pixelSize.Height * (1 - CacheTolerance)) { // Already cached return(cacheEntry.Item2); } else { // Dispose/remove current entry cacheEntry.Item2.Bitmap?.Dispose(); ImageSourceCache.Remove(key); } } // Convert to an SKBitmapImageSource using (SKImage image = SKImage.FromPicture(svg.Picture, pixelSize, drawMatrix)) { SKBitmapImageSource imageSource = new SKBitmapImageSource() { Bitmap = SKBitmap.FromImage(image) }; ImageSourceCache.Add(key, Tuple.Create(pixelSize, imageSource)); return(imageSource); } }
//Create the event handler void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; DriveViewModel vm = this.BindingContext as DriveViewModel; if (vm == null) { return; } using (var webClient = new WebClient()) { var canvas = surface.Canvas; var stream = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/img.jpg?timestamp={DateTime.Now.Ticks}"); var img = SKBitmap.Decode(stream); SKRect bounds = canvas.LocalClipBounds; float xRatio = (float)info.Width / (float)img.Width; float yRatio = (float)info.Height / (float)img.Height; canvas.Scale(xRatio, yRatio); canvas.DrawBitmap(img, 0, 0); //, canvas.LocalClipBounds); if (vm.ShowGrass) { try { var streamGrass = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/grass.svg?timestamp={DateTime.Now.Ticks}&layerItems=detection&layerItems=surface&layerItems=robotMotionState&layerItems=inferenceType"); //SKSvg svgGrass = new SkiaSharp.SKSvg(); SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg(); svg.Load(new MemoryStream(streamGrass)); canvas.DrawPicture(svg.Picture); } catch (Exception err) { } } if (vm.ShowScene) { try { var streamScene = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/scene.svg?timestamp={DateTime.Now.Ticks}&layerItems=GeneralObjectDetectionTransformer&layerItems=ToadiObjectDetectionTransformer&layerItems=ChargingStationPoseTransformer"); SkiaSharp.Extended.Svg.SKSvg svgScene = new SkiaSharp.Extended.Svg.SKSvg(); svgScene.Load(new MemoryStream(streamScene)); canvas.DrawPicture(svgScene.Picture); } catch (Exception err) { } } img.Dispose(); canvas.Dispose(); //using (var canvas = surface.Canvas) { // // use KBitmap.Decode to decode the byte[] in jpeg format // using (var bitmap = SKBitmap.Decode(stream)) { // using (var paint = new SKPaint()) { // // clear the canvas / fill with black // //canvas.DrawColor(SKColors.Black); // canvas.DrawBitmap(bitmap, canvas.LocalClipBounds); // //canvas.DrawBitmap(bitmap, 0, 0, paint); // SKRect.Create(640, 480) // //canvas.DrawBitmap(bitmap, SKRect.Create(640, 480), SKRect.Create((float)canvasView.Width, (float)canvasView.Height)); // } // } //} } }
/// <summary> /// Paint checkbox /// </summary> /// <param name="e"></param> protected override void OnPaintSelectionElement(SKPaintSurfaceEventArgs e) { if (_checkMarkSvg == null && string.IsNullOrEmpty(CheckMarkIconAssemblyName) == false && string.IsNullOrEmpty(CheckMarkIconResourceKey) == false) { _checkMarkSvg = SvgImage.GetSvgImage(CheckMarkIconAssemblyName, CheckMarkIconResourceKey); } Rectangle checkBoxAvailableLocation = new Rectangle(); Rectangle availableSpace = new Rectangle(EllipseDiameter, EllipseDiameter, Width, Height - Padding.VerticalThickness); if (CheckBoxLocation == HorizontalLocations.Left) { checkBoxAvailableLocation = availableSpace; } else { checkBoxAvailableLocation = new Rectangle(availableSpace.Width - CheckBoxWidthRequest - CheckBoxMargin.HorizontalThickness + EllipseDiameter, EllipseDiameter, availableSpace.Width, availableSpace.Height); } Rectangle checkBoxActualLocation = CheckBoxActualLocation(checkBoxAvailableLocation); float skCheckBoxBorderThickness = (float)CheckBoxBorderThickness * DeviceScale; float skCheckBoxX = (float)checkBoxActualLocation.X * DeviceScale; float skCheckBoxY = (float)checkBoxActualLocation.Y * DeviceScale; float skCheckBoxWidth = (float)CheckBoxWidthRequest * DeviceScale; float skCheckBoxHeight = (float)CheckBoxHeightRequest * DeviceScale; float skCornerRadius = (float)CheckBoxCornerRadius * DeviceScale; SKMatrix checkMarkMatrix = new SKMatrix(); SKPoint checkMarkPosition = new SKPoint(); Size checkMarkIconSize = new Size(CheckBoxWidthRequest - CheckMarkIconMargin.HorizontalThickness, CheckBoxHeightRequest - CheckMarkIconMargin.VerticalThickness); float scale = SvgImage.CalculateScale(_checkMarkSvg.Picture.CullRect.Size, checkMarkIconSize.Width, checkMarkIconSize.Height); Size actualCheckMarkIconSize = new Size(_checkMarkSvg.Picture.CullRect.Width * scale, _checkMarkSvg.Picture.CullRect.Height * scale); scale = scale * DeviceScale; checkMarkPosition.X = (float)skCheckBoxX + (float)((CheckBoxWidthRequest - actualCheckMarkIconSize.Width) / 2) * DeviceScale; checkMarkPosition.Y = (float)skCheckBoxY + (float)((CheckBoxHeightRequest - actualCheckMarkIconSize.Height) / 2) * DeviceScale; checkMarkMatrix.SetScaleTranslate(scale, scale, checkMarkPosition.X, checkMarkPosition.Y); SKRect checkBoxPaintRect = new SKRect(skCheckBoxX + skCheckBoxBorderThickness / 2, skCheckBoxY + skCheckBoxBorderThickness / 2, skCheckBoxX + skCheckBoxWidth - skCheckBoxBorderThickness / 2, skCheckBoxY + skCheckBoxHeight - skCheckBoxBorderThickness / 2); if (EllipseDiameter > 0 && _toggledAnimationProcess > 0 && _toggledAnimationProcess < 1 && IsEllipseAnimationEnabled) { SKPaint ellipsePaint = new SKPaint() { IsAntialias = true, Style = SKPaintStyle.Fill, }; if (_toggledAnimationProcess <= 0.5) { ellipsePaint.Color = EllipseColor.MultiplyAlpha(_toggledAnimationProcessWithoutEasing * 2).ToSKColor(); } else { ellipsePaint.Color = EllipseColor.MultiplyAlpha(1 - (_toggledAnimationProcessWithoutEasing - 0.5) * 2).ToSKColor(); } e.Surface.Canvas.DrawCircle(new SKPoint(checkBoxPaintRect.MidX, checkBoxPaintRect.MidY), (float)(EllipseDiameter / 2) * DeviceScale, ellipsePaint); } Color backgroundColor = Color.Transparent; if (CheckBoxBackgroundColor != null && CheckBoxBackgroundColor != Color.Transparent && ToggledCheckBoxBackgroundColor != null && ToggledCheckBoxBackgroundColor != Color.Transparent) { backgroundColor = AnimationUtils.ColorTransform(_toggledAnimationProcess, CheckBoxBackgroundColor, ToggledCheckBoxBackgroundColor); } else if ((CheckBoxBackgroundColor == null || CheckBoxBackgroundColor == Color.Transparent) && ToggledCheckBoxBackgroundColor != null && ToggledCheckBoxBackgroundColor != Color.Transparent) { backgroundColor = ToggledCheckBoxBackgroundColor; } else { backgroundColor = CheckBoxBackgroundColor; } SKPaint checkBoxBackgroundPaint = new SKPaint { Style = SKPaintStyle.Fill, IsAntialias = true, Color = backgroundColor.ToSKColor(), }; SKRect rect = new SKRect( skCheckBoxX + skCheckBoxBorderThickness, skCheckBoxY + skCheckBoxBorderThickness, skCheckBoxX + skCheckBoxWidth - skCheckBoxBorderThickness, skCheckBoxY + skCheckBoxHeight - skCheckBoxBorderThickness); e.Surface.Canvas.Save(); SKRect r = SKRect.Create(rect.Left, rect.Top, rect.Width, rect.Height); if (_toggledAnimationProcess <= 0.75) { float v = (float)(_toggledAnimationProcess * (1 / 0.75)); r.Inflate(-rect.Width * v / 2, -rect.Height * v / 2); e.Surface.Canvas.ClipRect(r, SKClipOperation.Difference); } e.Surface.Canvas.DrawRoundRect(checkBoxPaintRect, skCornerRadius, skCornerRadius, checkBoxBackgroundPaint); e.Surface.Canvas.Restore(); SKPaint checkBoxBorderPaint = new SKPaint { Style = SKPaintStyle.Stroke, IsAntialias = true, StrokeWidth = skCheckBoxBorderThickness, Color = AnimationUtils.ColorTransform(_toggledAnimationProcess, CheckBoxBorderColor, ToggledCheckBoxBorderColor).ToSKColor(), }; e.Surface.Canvas.DrawRoundRect(checkBoxPaintRect, skCornerRadius, skCornerRadius, checkBoxBorderPaint); using (var paint = new SKPaint()) { Color color = Color.Transparent; if (_toggledAnimationProcess > 0.75) { float v = (float)((_toggledAnimationProcess - 0.75) * (1 / 0.25)); color = AnimationUtils.ColorTransform(v, CheckMarkIconColor, ToggledCheckMarkIconColor); } if (color != Color.Transparent) { paint.ColorFilter = SKColorFilter.CreateBlendMode(color.ToSKColor(), SKBlendMode.SrcIn); paint.Style = SKPaintStyle.Fill; paint.IsAntialias = true; e.Surface.Canvas.DrawPicture(_checkMarkSvg.Picture, ref checkMarkMatrix, paint); } } }
public static void CreateOgImage( [QueueTrigger("ClassifyResultCreate")] string input, [Table("ClassifyResult", "ja-en", "{queueTrigger}")] ResponseTableEntity tableEntity, [Blob("classifyresultogimage/{queueTrigger}.png", FileAccess.Write)] Stream imageStream, ILogger log) { log.LogInformation($"Handle {input}"); var response = JsonConvert.DeserializeObject <Response>(tableEntity.ResponseData); var barFactor = 600; var adultBar = response.Categories.First(x => x.Name == "Adult").Score *barFactor; var racyBar = response.Categories.First(x => x.Name == "Racy").Score *barFactor; var offensiveBar = response.Categories.First(x => x.Name == "Offensive").Score *barFactor; var svgString = $@"<?xml version=""1.0""?> <svg width=""960"" height=""480"" xmlns=""http://www.w3.org/2000/svg"" xmlns:svg=""http://www.w3.org/2000/svg""> <g class=""layer""> <text fill=""#000000"" font-family=""Meiryo"" font-size=""48"" id=""svg_1"" stroke=""#000000"" stroke-width=""0"" text-anchor=""start"" x=""32"" y=""48"">JapaniseTextClassifier</text> <switch> <foreignObject x=""64"" y=""64"" width=""832"" height=""240""> <p xmlns=""http://www.w3.org/1999/xhtml"" style=""font-size: 24px; font-family: Meiryo;""> {response.Request.Text} </p> </foreignObject> <text fill=""#000000"" font-family=""Meiryo"" font-size=""24"" id=""svg_2"" stroke=""#000000"" stroke-width=""0"" text-anchor=""start"" x=""64"" y=""96"">{response.Request.Text}</text> </switch> <text fill=""#000000"" font-family=""Meiryo"" font-size=""24"" id=""svg_3"" stroke=""#000000"" stroke-width=""0"" text-anchor=""start"" x=""64"" y=""370"">Adult</text> <text fill=""#000000"" font-family=""Meiryo"" font-size=""24"" id=""svg_4"" stroke=""#000000"" stroke-width=""0"" text-anchor=""start"" x=""64"" y=""410"">Racy</text> <text fill=""#000000"" font-family=""Meiryo"" font-size=""24"" id=""svg_5"" stroke=""#000000"" stroke-width=""0"" text-anchor=""start"" x=""64"" y=""450"">Offensive</text> <rect fill=""#000000"" height=""32"" id=""svg_6"" stroke=""#000000"" stroke-width=""5"" width=""{adultBar}"" x=""240"" y=""340""/> <rect fill=""#000000"" height=""32"" id=""svg_7"" stroke=""#000000"" stroke-width=""5"" width=""{racyBar}"" x=""240"" y=""380""/> <rect fill=""#000000"" height=""32"" id=""svg_8"" stroke=""#000000"" stroke-width=""5"" width=""{offensiveBar}"" x=""240"" y=""420""/> </g> </svg>"; var svg = new SkiaSharp.Extended.Svg.SKSvg(); var pict = svg.Load(new MemoryStream(Encoding.UTF8.GetBytes(svgString))); 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); var quality = 90; var skdata = img.Encode(SkiaSharp.SKEncodedImageFormat.Png, quality); skdata.SaveTo(imageStream); log.LogInformation(svgString); }