internal static SKBitmap PaddingImage(SKBitmap original, int paddedWidth, int paddedHeight, bool isOpaque) { // setup new bitmap and optionally clear var bitmap = new SKBitmap(paddedWidth, paddedHeight, isOpaque); var canvas = new SKCanvas(bitmap); if (isOpaque) { canvas.Clear(new SKColor(255, 255, 255)); // we could make this color a resizeParam } else { canvas.Clear(SKColor.Empty); } // find co-ords to draw original at var left = original.Width < paddedWidth ? (paddedWidth - original.Width) / 2 : 0; var top = original.Height < paddedHeight ? (paddedHeight - original.Height) / 2 : 0; var drawRect = new SKRectI { Left = left, Top = top, Right = original.Width + left, Bottom = original.Height + top }; // draw original onto padded version canvas.DrawBitmap(original, drawRect); canvas.Flush(); canvas.Dispose(); original.Dispose(); return(bitmap); }
private SKBitmap Pad(SKBitmap original, int paddedWidth, int paddedHeight, bool isOpaque) { // setup new bitmap and optionally clear var bitmap = new SKBitmap(paddedWidth, paddedHeight, isOpaque); var canvas = new SKCanvas(bitmap); canvas.Clear(isOpaque ? new SKColor(255, 255, 255) : SKColor.Empty); // find co-ords to draw original at var left = original.Width < paddedWidth ? (paddedWidth - original.Width) / 2 : 0; var top = original.Height < paddedHeight ? (paddedHeight - original.Height) / 2 : 0; var drawRect = new SKRectI { Left = left, Top = top, Right = original.Width + left, Bottom = original.Height + top }; // draw original onto padded version canvas.DrawBitmap(original, drawRect); canvas.Flush(); canvas.Dispose(); original.Dispose(); return(bitmap); }
public override void Dispose() { _canvas.Dispose(); _surface.Dispose(); _framebuffer.Dispose(); base.Dispose(); }
public override void Dispose() { if (_skiaCanvas != null) { _skiaCanvas.Dispose(); _skiaCanvas = null; } if (_surface != null) { _surface.Dispose(); _surface = null; } if (_image != null) { _image.Dispose(); _image = null; } if (_bitmap != null && _disposeBitmap) { _bitmap.Dispose(); _bitmap = null; } _canvas = null; base.Dispose(); }
public void SetBounds(int AWidth, int AHeight) { // Prevent divisions by zero downstream if (AWidth == 0) { AWidth = 1; } if (AHeight == 0) { AHeight = 1; } int PrevDisplayWidth = 1; int PrevDisplayHeight = 1; if (BitmapCanvas != null) { PrevDisplayWidth = BitmapCanvas.Width; PrevDisplayHeight = BitmapCanvas.Height; } BitmapCanvas?.Dispose(); BitmapCanvas = new SKBitmap(AWidth, AHeight, SKColorType.Rgba8888, SKAlphaType.Unpremul); DrawCanvas?.Dispose(); DrawCanvas = new SKCanvas(BitmapCanvas); if (BitmapCanvas != null) { if (PrevDisplayWidth > 0 && PrevDisplayHeight > 0) { if (SquareAspect) { if (HoldOriginOnResize) { SetWorldBounds(OriginX, OriginY, OriginX + WidthX * ((double)AWidth / (double)PrevDisplayWidth), OriginY + WidthY * ((double)AHeight / (double)PrevDisplayHeight), 0); } else { SetWorldBounds(LimitX - WidthX * ((double)AWidth / (double)PrevDisplayWidth), LimitY - WidthY * ((double)AHeight / (double)PrevDisplayHeight), LimitX, LimitY, 0); } } else { SetWorldBounds(OriginX, OriginY, OriginX + WidthX, OriginY + WidthY, 0); } } } CalculateXYOffsets(); }
public void Dispose() { if (_canvas != null) { _canvas?.Flush(); _canvas?.Dispose(); _canvas = null; } }
internal static SKBitmap WatermarkText(SKBitmap original, ResizeParams resizeParams, WatermarkTextModel watermarkText) { var toBitmap = new SKBitmap(original.Width, original.Height); var canvas = new SKCanvas(toBitmap); // Draw a bitmap rescaled var paint = new SKPaint(); //paint.Typeface = SKTypeface.FromFamilyName("Arial"); paint.TextSize = watermarkText.TextSize; paint.TextAlign = watermarkText.TextAlign.GetSKTextAlign(); if (watermarkText.IsVerticalText) { paint.IsVerticalText = true; } else { paint.IsLinearText = true; } if (watermarkText.Type == 2) { paint.IsStroke = true; paint.StrokeWidth = watermarkText.StrokeWidth; paint.StrokeCap = SKStrokeCap.Round; } paint.Style = watermarkText.Type.GetSKPaintStyle(); paint.FilterQuality = watermarkText.Quality.GetSKFilterQuality(); paint.TextSkewX = watermarkText.TextSkewX; paint.IsAntialias = true; //https://www.color-hex.com/ if (SKColor.TryParse(watermarkText.Color, out SKColor color)) { paint.Color = color; } else { paint.Color = SKColors.Black; } canvas.DrawBitmap(original, 0, 0); var x = watermarkText.PositionMeasureType == 1 ? watermarkText.X : watermarkText.X.ToPixel(original.Width); var y = watermarkText.PositionMeasureType == 1 ? watermarkText.Y : watermarkText.Y.ToPixel(original.Height); canvas.DrawText(watermarkText.Value, x, y, paint); canvas.Flush(); canvas.Dispose(); paint.Dispose(); original.Dispose(); return(toBitmap); }
/// <summary> /// Gets the resulting graphics encoded as a PNG image in a byte array. /// <para> /// The canvas can no longer be used for drawing after calling this method.</para> /// </summary> /// <returns>The byte array containing the PNG image</returns> public override byte[] ToByteArray() { _canvas.Dispose(); _canvas = null; byte[] result; using (var image = SKImage.FromBitmap(_bitmap)) using (var data = image.Encode(SKEncodedImageFormat.Png, 90)) using (var imageDataStream = data.AsStream()) { var buffer = new MemoryStream(); PngProcessor.InsertDpi(imageDataStream, buffer, _dpi); result = buffer.ToArray(); } Close(); return(result); }
void RenderWithSkia() { int width = glControl1.Width; int height = glControl1.Height; if (field == null || field.width != width || field.height != height) { field = new Starfield.Field(100_000, width, height); } field.StepForward(); // Create a Skia surface using the OpenGL control SKColorType colorType = SKColorType.Rgba8888; GRContext contextOpenGL = GRContext.Create(GRBackend.OpenGL, GRGlInterface.CreateNativeGlInterface()); GL.GetInteger(GetPName.FramebufferBinding, out var framebuffer); GRGlFramebufferInfo glInfo = new GRGlFramebufferInfo((uint)framebuffer, colorType.ToGlSizedFormat()); GL.GetInteger(GetPName.StencilBits, out var stencil); GRBackendRenderTarget renderTarget = new GRBackendRenderTarget(width, height, contextOpenGL.GetMaxSurfaceSampleCount(colorType), stencil, glInfo); SKSurface surface = SKSurface.Create(contextOpenGL, renderTarget, GRSurfaceOrigin.BottomLeft, colorType); SKCanvas canvas = surface.Canvas; // draw the starfield var paint = new SKPaint { Color = SKColors.White, IsAntialias = true }; canvas.Clear(SKColors.Black); foreach (Starfield.Star star in field.stars) { //canvas.DrawRect(star.X, star.Y, star.Size, star.Size, paint); canvas.DrawCircle(new SKPoint(star.X, star.Y), star.Size / 2, paint); } // Force a display surface.Canvas.Flush(); glControl1.SwapBuffers(); // dispose to prevent memory access violations while exiting renderTarget?.Dispose(); contextOpenGL?.Dispose(); canvas?.Dispose(); surface?.Dispose(); // update the FPS display renderCount += 1; double elapsedSeconds = (double)stopwatch.ElapsedMilliseconds / 1000; Text = string.Format("Rendered {0} frames in {1:0.00} seconds ({2:0.00} Hz)", renderCount, elapsedSeconds, renderCount / elapsedSeconds); }
public void Create(byte[] imageData) { var webClient = new WebClient(); //byte[] imageData = webClient.DownloadData("https://kasikornbank.com/SiteCollectionDocuments/about/img/logo/logo.png"); var resizeFactor = 0.5f; var bitmap = SKBitmap.Decode(imageData); var toBitmap = new SKBitmap((int)Math.Round(bitmap.Width * resizeFactor), (int)Math.Round(bitmap.Height * resizeFactor), bitmap.ColorType, bitmap.AlphaType); var canvas = new SKCanvas(toBitmap); canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor)); canvas.DrawBitmap(bitmap, 0, 0); canvas.ResetMatrix(); var font = SKTypeface.FromFamilyName("Arial"); var brush = new SKPaint { Typeface = font, TextSize = 64.0f, IsAntialias = true, Color = new SKColor(255, 255, 255, 255) }; canvas.DrawText("Resized!", 0, bitmap.Height * resizeFactor / 2.0f, brush); canvas.Flush(); var image = SKImage.FromBitmap(toBitmap); var data = image.Encode(SKEncodedImageFormat.Png, 90); DateTime now = DateTime.Now; string fileName = "Test"; //string fileName = ("{0}_{1}_{2}-{4}{5}{6}", now.Date,now.Month,now.Year,now.Hour,now.Minute,now.Second).ToString(); string extension = ".png"; Java.IO.File picturesDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); Java.IO.File folderDirectory = picturesDirectory; //Start Save using (var stream = new FileStream(Path.Combine(folderDirectory.ToString(), fileName + extension), FileMode.Create, FileAccess.Write)) data.SaveTo(stream); //End Save data.Dispose(); image.Dispose(); canvas.Dispose(); brush.Dispose(); font.Dispose(); toBitmap.Dispose(); bitmap.Dispose(); }
public static async Task SaveToDisk(string basePath, int i, SKBitmap bitmap, SKCanvas canvas) { using (var data = bitmap.Encode(SKEncodedImageFormat.Png, 80)) { // save the data to a stream using (var stream = File.OpenWrite(Path.Combine(basePath, $"{i.ToString("D8")}.png"))) data.SaveTo(stream); } // Release bitmap.Dispose(); canvas.Dispose(); }
void Render() { // Create a Skia surface using the OpenGL control int width = glControl1.Width; int height = glControl1.Height; SKColorType colorType = SKColorType.Rgba8888; GRContext contextOpenGL = GRContext.Create(GRBackend.OpenGL, GRGlInterface.CreateNativeGlInterface()); GL.GetInteger(GetPName.FramebufferBinding, out var framebuffer); GRGlFramebufferInfo glInfo = new GRGlFramebufferInfo((uint)framebuffer, colorType.ToGlSizedFormat()); GL.GetInteger(GetPName.StencilBits, out var stencil); GRBackendRenderTarget renderTarget = new GRBackendRenderTarget(width, height, contextOpenGL.GetMaxSurfaceSampleCount(colorType), stencil, glInfo); SKSurface surface = SKSurface.Create(contextOpenGL, renderTarget, GRSurfaceOrigin.BottomLeft, colorType); SKCanvas canvas = surface.Canvas; // draw some lines canvas.Clear(SKColor.Parse("#003366")); var paint = new SKPaint { Color = new SKColor(255, 255, 255, 50), IsAntialias = true }; for (int i = 0; i < 1_000; i++) { SKPoint ptA = new SKPoint(rand.Next(width), rand.Next(height)); SKPoint ptB = new SKPoint(rand.Next(width), rand.Next(height)); canvas.DrawLine(ptA, ptB, paint); } // Force a display surface.Canvas.Flush(); glControl1.SwapBuffers(); // dispose to prevent memory access violations while exiting renderTarget?.Dispose(); contextOpenGL?.Dispose(); canvas?.Dispose(); surface?.Dispose(); // update the FPS display renderCount += 1; double elapsedSeconds = (double)stopwatch.ElapsedMilliseconds / 1000; Text = string.Format("Rendered {0} frames in {1:0.00} seconds ({2:0.00} Hz)", renderCount, elapsedSeconds, renderCount / elapsedSeconds); }
/// <summary> /// Draws the footer and ends the current page. /// </summary> private static void EndPage() { if (_document == null) { return; } if (_canvas != null) { DrawFooter(); _canvas.Flush(); _document.EndPage(); _canvas.Dispose(); _canvas = null; } }
static void Main(string[] args) { var resizeFactor = 0.5f; var bitmap = SKBitmap.Decode("input.png"); var toBitmap = new SKBitmap((int)Math.Round(bitmap.Width * resizeFactor), (int)Math.Round(bitmap.Height * resizeFactor), bitmap.ColorType, bitmap.AlphaType); var canvas = new SKCanvas(toBitmap); // Draw a bitmap rescaled canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor)); canvas.DrawBitmap(bitmap, 0, 0); canvas.ResetMatrix(); var font = SKTypeface.FromFamilyName("Arial"); var brush = new SKPaint { Typeface = font, TextSize = 40.0f, IsAntialias = true, Color = new SKColor(255, 255, 255, 255) }; canvas.DrawText("Resized!", 0, bitmap.Height * resizeFactor / 2.0f, brush); canvas.Flush(); var image = SKImage.FromBitmap(toBitmap); var data = image.Encode(SKEncodedImageFormat.Png, 90); using (var stream = new FileStream("output.png", FileMode.Create, FileAccess.Write)) data.SaveTo(stream); data.Dispose(); image.Dispose(); canvas.Dispose(); brush.Dispose(); font.Dispose(); toBitmap.Dispose(); bitmap.Dispose(); }
public SKBitmap Render(int width, int height) { var w = width / MaxWidth; var h = height / MaxHeight; var bitmap = new SKBitmap(width, height, SKColorType.Bgra8888, SKAlphaType.Premul); this.SpriteSheetData = new SpriteSheetData(); this.SpriteSheetData.sprites = new SpriteData[OriginImages.Count]; using (var canvas = new SKCanvas(bitmap)) { canvas.Clear(); for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++) { var idx = y * w + x; if (idx >= Images.Count) goto End; canvas.DrawBitmap(Images[idx], x * MaxWidth, y * MaxHeight); OnProgress?.Invoke((double)(idx + 1) / Images.Count); SpriteSheetData.sprites[idx] = new SpriteData() { x = x * MaxWidth, y = (h - 1 - y) * MaxHeight, width = MaxWidth, height = MaxHeight, pivotX = MaxWidth / 2, pivotY = MaxHeight / 2 }; } } End: canvas.Flush(); canvas.Dispose(); } return bitmap; }
protected override void OnDestroyingContext() { base.OnDestroyingContext(); lastSize = default; canvas?.Dispose(); canvas = null; surface?.Dispose(); surface = null; renderTarget?.Dispose(); renderTarget = null; glInfo = default; context?.AbandonContext(false); context?.Dispose(); context = null; glInterface?.Dispose(); glInterface = null; }
/// <summary> /// Dispose resources. /// </summary> public void Dispose() { _bitmap?.Dispose(); _canvas?.Dispose(); }
void OnPaintSurface(SKSurface surface, int width, int height) { // Get the canvas SKCanvas canvas = surface.Canvas; // These two dimensions should be the same. int canvasSize = Math.Min(width, height); // If bitmap does not exist, create it if (bitmap == null) { // Set three fields bitmapSize = canvasSize; bitmap = new SKBitmap(bitmapSize, bitmapSize); bitmapCanvas = new SKCanvas(bitmap); // Establishes circular clipping and colors background PrepBitmap(bitmapCanvas, bitmapSize); } // If the canvas has become larger, make a new bitmap of that size. else if (bitmapSize < canvasSize) { // New versions of the three fields int newBitmapSize = canvasSize; SKBitmap newBitmap = new SKBitmap(newBitmapSize, newBitmapSize); SKCanvas newBitmapCanvas = new SKCanvas(newBitmap); // New circular clipping and background PrepBitmap(newBitmapCanvas, newBitmapSize); // Copy old bitmap to new bitmap float diff = (newBitmapSize - bitmapSize) / 2f; newBitmapCanvas.DrawBitmap(bitmap, diff, diff); // Dispose old bitmap and its canvas bitmapCanvas.Dispose(); bitmap.Dispose(); // Set fields to new values bitmap = newBitmap; bitmapCanvas = newBitmapCanvas; bitmapSize = newBitmapSize; } // Clear the canvas canvas.Clear(SKColors.White); // Set the rotate transform float radius = canvasSize / 2; canvas.RotateDegrees(angle, radius, radius); // Set a circular clipping area clipPath.Reset(); clipPath.AddCircle(radius, radius, radius); canvas.ClipPath(clipPath); // Draw the bitmap float offset = (canvasSize - bitmapSize) / 2f; canvas.DrawBitmap(bitmap, offset, offset); // Draw the cross hairs canvas.DrawLine(radius, 0, radius, canvasSize, thinLinePaint); canvas.DrawLine(0, radius, canvasSize, radius, thinLinePaint); }
public void Destroy() { nativePaint.Dispose(); nativeCanvas.Dispose(); nativeSurface.Dispose(); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { canvas?.Dispose(); canvas = null; bitmap?.Dispose(); bitmap = null; base.Dispose(); }
public void Dispose() { Bitmap.Dispose(); Canvas.Dispose(); }
private async Task <Stream> GetQueryResultImage() { Stopwatch watchDraw = new Stopwatch(); watchDraw.Start(); // todo make dynamic int width = Width; int height = 10000; SKBitmap bitmap = new SKBitmap(width, height); // TODO insert into constructor SKCanvas canvas = new SKCanvas(bitmap); canvas.Clear(DrawingHelper.DiscordBackgroundColor); int padding = 20; int xSize = width - padding * 2; if (Header.Count == 0) { // TODO draw no results on image //await Context.Channel.SendMessageAsync("No results", false, null, null, null, new Discord.MessageReference(Context.Message.Id)); return(null); } int cellWidth = xSize / Header.Count; int currentHeight = padding; List <int> widths = DefineTableCellWidths(cellWidth, DrawingHelper.TitleTextPaint, DrawingHelper.DefaultTextPaint); string cellWithInfo = "normal" + cellWidth + " " + string.Join(", ", widths); //await Context.Channel.SendMessageAsync(cellWithInfo, false, null, null, null, new Discord.MessageReference(Context.Message.Id)); currentHeight = DrawRow(canvas, Header, -1, padding, currentHeight + 10, widths, true); int failedDrawLineCount = 0; int rowId = 0; foreach (var row in Data) { try { canvas.DrawLine(padding, currentHeight - 13, Math.Max(width - padding, 0), currentHeight - 13, DrawingHelper.DefaultDrawing); } catch (Exception ex) { failedDrawLineCount++; } try { currentHeight = DrawRow(canvas, row, rowId, padding, currentHeight, widths); currentHeight += 5; } catch (Exception ex) { // TODO send exception //Context.Channel.SendMessageAsync(ex.ToString()); break; } rowId++; } try { canvas.DrawLine(padding, currentHeight - 13, Math.Max(width - padding, 0), currentHeight - 13, DrawingHelper.DefaultDrawing); } catch (Exception ex) { failedDrawLineCount++; } if (failedDrawLineCount > 0) { //Context.Channel.SendMessageAsync($"Failed to draw {failedDrawLineCount} lines, widths: {string.Join(",", widths)}"); } int currentWidth = padding; foreach (var curWidth in widths) { canvas.DrawLine(currentWidth, padding - 5, currentWidth, currentHeight - 13, DrawingHelper.DefaultDrawing); currentWidth += curWidth; } canvas.DrawLine(currentWidth, padding - 5, currentWidth, currentHeight - 13, DrawingHelper.DefaultDrawing); watchDraw.Stop(); // canvas.DrawText($"{AdditionalString} DrawTime: {watchDraw.ElapsedMilliseconds.ToString("N0")}ms", new SKPoint(padding, currentHeight + padding), DrawingHelper.TitleTextPaint); // TODO Different color for text //List<int> rowHeight = new List<int>(); //Rectangle DestinationRectangle = new Rectangle(10, 10, cellWidth, 500); //var size = Graphics.MeasureCharacterRanges("", drawFont2, DestinationRectangle, null); //Graphics.DrawString($"{(int)((maxValue / yNum) * i)}", drawFont2, b, new Point(40, 10 + ySize - (ySize / yNum) * i)); bitmap = DrawingHelper.CropImage(bitmap, new SKRect(0, 0, Width, currentHeight + padding * 3)); var stream = CommonHelper.GetStream(bitmap); bitmap.Dispose(); canvas.Dispose(); return(stream); }
private List <int> DefineTableCellWidths(int normalCellWidth, SKPaint headerPaint, SKPaint normalPaint) { var bitmap = new SKBitmap(2000, 2000); // TODO insert into constructor SKCanvas canvas = new SKCanvas(bitmap); canvas.Clear(DrawingHelper.DiscordBackgroundColor); int[] maxWidthNeeded = new int[Header.Count]; // the minimum size is the header text size for (int i = 0; i < Header.Count; i++) { var width = headerPaint.MeasureText(Header[i]); maxWidthNeeded[i] = (int)width + 10; } // find the max column size in the content for (int i = 0; i < maxWidthNeeded.Length; i++) { foreach (var row in Data) { var width = normalPaint.MeasureText(row[i]); int currentWidth = (int)width + 10; if (maxWidthNeeded[i] < currentWidth) { maxWidthNeeded[i] = currentWidth; } } } // find columns that need the flex property List <int> flexColumns = new List <int>(); int freeRoom = 0; int flexContent = 0; for (int i = 0; i < maxWidthNeeded.Length; i++) { if (maxWidthNeeded[i] > normalCellWidth) { flexColumns.Add(i); flexContent += maxWidthNeeded[i] - normalCellWidth; // only the oversize } else { freeRoom += normalCellWidth - maxWidthNeeded[i]; } } if (flexColumns.Count == 0) { // no columns need flex so we distribute all even for (int i = 0; i < maxWidthNeeded.Length; i++) { maxWidthNeeded[i] = normalCellWidth; } } else { // we need to distribute the free room over the flexContent by % foreach (var column in flexColumns) { float percentNeeded = (maxWidthNeeded[column] - normalCellWidth) / (float)flexContent; float gettingFreeSpace = freeRoom * percentNeeded; maxWidthNeeded[column] = normalCellWidth + (int)gettingFreeSpace; } } canvas.Dispose(); bitmap.Dispose(); return(maxWidthNeeded.ToList()); }
public void Dispose() { canvas.Dispose(); bitmap.Dispose(); }
public void Dispose() { _c?.Dispose(); }
private void Render(int cornerCount = 100, int maxVisibleDistance = 200) { // create the field if needed or if the size changed if (field == null || field.width != glControl1.Width || field.height != glControl1.Height) { field = new IntroAnimation.Field(glControl1.Width, glControl1.Height, cornerCount); } // step the field forward in time field.StepForward(3); // Create a Skia surface using the OpenGL control SKColorType colorType = SKColorType.Rgba8888; GRContext contextOpenGL = GRContext.Create(GRBackend.OpenGL, GRGlInterface.CreateNativeGlInterface()); GL.GetInteger(GetPName.FramebufferBinding, out var framebuffer); GRGlFramebufferInfo glInfo = new GRGlFramebufferInfo((uint)framebuffer, colorType.ToGlSizedFormat()); GL.GetInteger(GetPName.StencilBits, out var stencil); GRBackendRenderTarget renderTarget = new GRBackendRenderTarget(glControl1.Width, glControl1.Height, contextOpenGL.GetMaxSurfaceSampleCount(colorType), stencil, glInfo); SKSurface surface = SKSurface.Create(contextOpenGL, renderTarget, GRSurfaceOrigin.BottomLeft, colorType); SKCanvas canvas = surface.Canvas; // draw the stuff var bgColor = field.GetBackgroundColor(); canvas.Clear(new SKColor(bgColor.R, bgColor.G, bgColor.B)); // draw circles at every corner var paint = new SKPaint { Color = new SKColor(255, 255, 255), IsAntialias = true }; float radius = 2; for (int cornerIndex = 0; cornerIndex < field.corners.Length; cornerIndex++) { canvas.DrawCircle((float)field.corners[cornerIndex].X, (float)field.corners[cornerIndex].Y, radius, paint); } // draw lines between every corner and every other corner for (int i = 0; i < field.corners.Length; i++) { for (int j = 0; j < field.corners.Length; j++) { double distance = field.GetDistance(i, j); if (distance < maxVisibleDistance && distance != 0) { SKPoint pt1 = new SKPoint((float)field.corners[i].X, (float)field.corners[i].Y); SKPoint pt2 = new SKPoint((float)field.corners[j].X, (float)field.corners[j].Y); double distanceFraction = distance / maxVisibleDistance; byte alpha = (byte)(255 - distanceFraction * 256); var linePaint = new SKPaint { Color = new SKColor(255, 255, 255, alpha), IsAntialias = true }; canvas.DrawLine(pt1, pt2, linePaint); } } } // Force a display surface.Canvas.Flush(); glControl1.SwapBuffers(); // dispose to prevent memory access violations while exiting renderTarget?.Dispose(); contextOpenGL?.Dispose(); canvas?.Dispose(); surface?.Dispose(); // update the FPS display Text = field.GetBenchmarkMessage(); }
public void Dispose() { Result?.Dispose(); _canvas?.Dispose(); _surface?.Dispose(); }
public void Dispose() { textPaint.Dispose(); canvas.Dispose(); Bitmap.Dispose(); }
public void PostProcess() { for (var i = 0; i < Images.Count; i++) if (Images[i] != OriginImages[i]) Images[i].Dispose(); Images = OriginImages; if(Reverse) { Images = Images.Select((originImg) => { var bitmap = new SKBitmap(originImg.Width, originImg.Height, SKColorType.Bgra8888, SKAlphaType.Premul); using (var canvas = new SKCanvas(bitmap)) { canvas.Clear(); canvas.Scale(-1, 1); canvas.DrawBitmap(originImg, new SKRectI(0, 0, originImg.Width, originImg.Height), new SKRectI(-originImg.Width, 0, 0, originImg.Height)); canvas.Flush(); canvas.Dispose(); } return bitmap; }).ToList(); } if(ClipTransparent) { var clipList = new SKRectI[Images.Count]; for (var i = 0; i < Images.Count; i++) { var bitmap = Images[i]; var clip = new SKRectI(); if (ClipTransparent) { // Clip X for (var x = 0; x < bitmap.Width; x++) { if (!ColumnTransparentScan(bitmap, x)) { clip.Left = x; break; } } for (var x = bitmap.Width - 1; x >= 0; x--) { if (!ColumnTransparentScan(bitmap, x)) { clip.Right = x + 1; break; } } // Clip Y for (var y = 0; y < bitmap.Height; y++) { if (!RowTransparentScan(bitmap, y)) { clip.Top = y; break; } } for (var y = bitmap.Height - 1; y >= 0; y--) { if (!RowTransparentScan(bitmap, y)) { clip.Bottom = y + 1; break; } } } clipList[i] = clip; } var minX = clipList.Select(rect => rect.Left).Min(); var minY = clipList.Select(rect => rect.Top).Min(); var images = new List<SKBitmap>(); for (var i = 0; i < Images.Count; i++) { var clip = clipList[i]; clip.Left = minX; clip.Top = minY; var bitmap = new SKBitmap(clip.Width, clip.Height, SKColorType.Bgra8888, SKAlphaType.Premul); using (var canvas = new SKCanvas(bitmap)) { canvas.Clear(); canvas.DrawBitmap(Images[i], clip, new SKRectI(0, 0, clip.Width, clip.Height)); canvas.Flush(); canvas.Dispose(); } images.Add(bitmap); if (Images != OriginImages) Images[i].Dispose(); } Images = images; } }
private byte[] CreateImage() { this.GetType().Assembly.GetManifestResourceNames(); var assembly = typeof(MainPage).GetTypeInfo().Assembly; var webClient = new WebClient(); byte[] imageData = webClient.DownloadData("https://kasikornbank.com/SiteCollectionDocuments/about/img/logo/logo.png"); var resizeFactor = 1f; SKBitmap bitmap = SKBitmap.Decode(imageData); var canvasHeight = (int)Math.Round(bitmap.Height * resizeFactor) + 100; var canvasWidth = (int)Math.Round(bitmap.Width * resizeFactor) + 20; toBitmap = new SKBitmap(canvasWidth, canvasHeight, bitmap.ColorType, bitmap.AlphaType); canvas = new SKCanvas(toBitmap); canvas.Clear(SKColors.White); canvas.SetMatrix(SKMatrix.MakeScale(resizeFactor, resizeFactor)); SKPaint grayscalePaint = new SKPaint() { ColorFilter = SKColorFilter.CreateColorMatrix(new float[] { 0.95f, 0.10f, 0.10f, 0, 0, 0.10f, 0.95f, 0.10f, 0, 0, 0.10f, 0.10f, 0.95f, 0, 0, 0, 0, 0, 1, 0 }) }; canvas.DrawBitmap(bitmap, 10, 50, grayscalePaint); canvas.ResetMatrix(); var fontStream = assembly.GetManifestResourceStream("ReceiptMaker.Media.THSarabunNew.ttf"); var font = SKTypeface.FromStream(fontStream); var boldFontStream = assembly.GetManifestResourceStream("ReceiptMaker.Media.THSarabunNewBold.ttf"); var boldFont = SKTypeface.FromStream(boldFontStream); var headerBrush = new SKPaint { Typeface = boldFont, TextSize = 50.0f, IsAntialias = true, StrokeWidth = 10.0f, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Center, TextEncoding = SKTextEncoding.Utf32 }; var subheaderBrush = new SKPaint { Typeface = font, TextSize = 40.0f, IsAntialias = true, Color = new SKColor(115, 111, 110, 255), TextAlign = SKTextAlign.Center }; var bankNameBrush = new SKPaint { Typeface = font, TextSize = 45.0f, IsAntialias = true, Color = new SKColor(115, 111, 110, 255), TextAlign = SKTextAlign.Center }; var accountNumber = new SKPaint { Typeface = boldFont, TextSize = 45.0f, IsAntialias = true, StrokeWidth = 10.0f, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Center }; var dateNumberDetailHeaderBrush = new SKPaint { Typeface = font, TextSize = 40.0f, IsAntialias = true, StrokeWidth = 10.0f, Color = new SKColor(115, 111, 110, 255), TextAlign = SKTextAlign.Center }; var dateNumberDetailBrush = new SKPaint { Typeface = boldFont, TextSize = 40.0f, IsAntialias = true, StrokeWidth = 10.0f, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Center }; var costDetailBrush = new SKPaint { Typeface = boldFont, TextSize = 40.0f, IsAntialias = true, StrokeWidth = 10.0f, Color = new SKColor(0, 0, 0, 255), TextAlign = SKTextAlign.Center }; int scale = 14; canvas.DrawText("โอนเงินผ่าน K-Mobile Banking PLUS", bitmap.Width / 2, canvasHeight / scale * 1, headerBrush); canvas.DrawText("ทำรายการสำเร็จ", bitmap.Width / 2, canvasHeight / scale * 2, subheaderBrush); canvas.DrawText("จาก", bitmap.Width / 4, canvasHeight / scale * 3, bankNameBrush); canvas.DrawText("โอนเข้า", bitmap.Width / 4 * 3, canvasHeight / scale * 3, bankNameBrush); canvas.DrawText("ธ.กสิกรไทย", bitmap.Width / 4, canvasHeight / scale * 6, bankNameBrush); canvas.DrawText("ธ.กสิกรไทย", bitmap.Width / 4 * 3, canvasHeight / scale * 6, bankNameBrush); canvas.DrawText("XXX-2-XXXXX-X", bitmap.Width / 4, canvasHeight / scale * 7, accountNumber); canvas.DrawText("XXX-2-XXXXX-X", bitmap.Width / 4 * 3, canvasHeight / scale * 7, accountNumber); canvas.DrawText("นาย ชื่อ สกุล", bitmap.Width / 4 * 3, canvasHeight / scale * 8, bankNameBrush); canvas.DrawText("วันที่ทำรายการ", bitmap.Width / 4, canvasHeight / scale * 10, dateNumberDetailHeaderBrush); canvas.DrawText(DateTime.Now.ToString("dd/MM/yy hh:mm"), bitmap.Width / 4, canvasHeight / scale * 11, dateNumberDetailBrush); canvas.DrawText("เลขที่รายการ", bitmap.Width / 4 * 3, canvasHeight / scale * 10, dateNumberDetailHeaderBrush); canvas.DrawText("150805172258630", bitmap.Width / 4 * 3, canvasHeight / scale * 11, dateNumberDetailBrush); canvas.DrawText("จำนวนเงิน", bitmap.Width / 4, canvasHeight / scale * 13, dateNumberDetailHeaderBrush); canvas.DrawText("350.00 บาท", bitmap.Width / 4, canvasHeight / scale * 14, costDetailBrush); canvas.DrawText("ค่าธรรมเนียม", bitmap.Width / 4 * 3, canvasHeight / scale * 13, dateNumberDetailHeaderBrush); canvas.DrawText("0.00 บาท", bitmap.Width / 4 * 3, canvasHeight / scale * 14, costDetailBrush); canvas.Flush(); var image = SKImage.FromBitmap(toBitmap); var data = image.Encode(SKEncodedImageFormat.Png, 90); return(data.ToArray()); data.Dispose(); image.Dispose(); canvas.Dispose(); //brush.Dispose(); font.Dispose(); toBitmap.Dispose(); bitmap.Dispose(); }