예제 #1
0
        private void UpdateBitmap()
        {
            var resolutionScale = DisplayInformation.GetForCurrentView().ResolutionScale;
            var screenScale     = (float)resolutionScale / 100.0f;
            var width           = (int)(ActualWidth * screenScale);
            var height          = (int)(ActualHeight * screenScale);

            if (width == 0 || height == 0)
            {
                return;
            }

            IntPtr buff = Marshal.AllocCoTaskMem(width * height * 4);

            try {
                using (var surface = SKSurface.Create(width, height, SKColorType.N_32, SKAlphaType.Premul, buff, width * 4)) {
                    var skcanvas = surface.Canvas;
                    skcanvas.Scale(screenScale, screenScale);
                    using (new SKAutoCanvasRestore(skcanvas, true)) {
                        skiaView.SendDraw(skcanvas);
                    }
                }

                var pixels = new byte[width * height * 4];
                Marshal.Copy(buff, pixels, 0, pixels.Length);

                var bitmap = new WriteableBitmap(width, height);

                var stream = bitmap.PixelBuffer.AsStream();
                stream.Seek(0, SeekOrigin.Begin);
                stream.Write(pixels, 0, pixels.Length);

                bitmap.Invalidate();

                var b = bitmap;
                Background = new ImageBrush {
                    ImageSource = b,
                    AlignmentX  = AlignmentX.Center,
                    AlignmentY  = AlignmentY.Center,
                    Stretch     = Stretch.Fill
                };
            } finally {
                if (buff != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(buff);
                }
            }
        }
예제 #2
0
        public override string Encode(string barcode)
        {
            // Barcode checks
            Barcode = Validate(barcode, 8);
            CheckCharset(Barcode);

            // Bars encode
            var bars = EncodeBars(Barcode);

            // Calculate drawing data
            var scale       = Math.Max(Options.Scale, 0);
            var margin      = 2 * scale;
            var width       = scale * bars.Length + margin * 2;
            var height      = scale * Options.Height + margin * 2;
            var barsHeights = new[] { (int)((height - margin * 2) * 0.76), height - margin * 2 };

            // Generate barcode image
            var surface = SKSurface.Create(new SKImageInfo(width, height));

            using (var canvas = surface.Canvas)
            {
                // Draw bg color
                canvas.Clear(Options.BackgroundColor);

                var brush = new SKPaint
                {
                    Color    = Options.Color,
                    IsStroke = false,
                };

                var posX = margin;
                for (var i = 0; i < bars.Length; i++)
                {
                    // Draw bars
                    if (bars[i] == '1')
                    {
                        canvas.DrawRect(posX, margin, scale, barsHeights[_barsHeight[i]], brush);
                    }

                    posX += scale;
                }

                if (Options.DrawText)
                {
                    // Draw texts
                    var font = new SKFont(SKTypeface.FromFamilyName(Options.Font, Options.FontStyle), 9 * scale);
#if NET6_0_OR_GREATER
                    var leftText  = Barcode[..4];
예제 #3
0
        public Chunk(ChunkData chunkData) : base(
                (float)chunkData.TopLeft.X,
                (float)chunkData.TopLeft.Y,
                chunkData.Size * AppSettings.BlockSizeU * ORoot.ScreenUnit,
                chunkData.Size * AppSettings.BlockSizeU * ORoot.ScreenUnit)
        {
            var blockSpriteProvider = GameServiceLocator.Instance.Get <BlockSpriteProvider>();

            _logger = GameServiceLocator.Instance.Get <Logger>();

            ChunkData = chunkData;

            _paint = new SKPaint()
            {
                Color = new SKColor(255, 255, 255)
            };

            var surface = SKSurface.Create(
                (int)Width,
                (int)Height,
                SKColorType.Rgba8888,
                SKAlphaType.Unpremul);

            var canvas = surface.Canvas;

            int blockCount = 0;

            foreach (var block in chunkData.Blocks)
            {
                var sprite = blockSpriteProvider.GetBlockSprite(block.Type, block);
                sprite.X = block.RelativeX * AppSettings.BlockSizeU * ORoot.ScreenUnit + sprite.Width / 2;
                sprite.Y = block.RelativeY * AppSettings.BlockSizeU * ORoot.ScreenUnit + sprite.Height / 2;

                sprite.SetCanvas(canvas);
                sprite.Render(new OViewState());

                blockCount++;
            }

            //_logger.Log($"block at {chunkData.X}-{chunkData.Y} draw {blockCount} sprites");

            _y -= AppSettings.BlockSizeU * ORoot.ScreenUnit / 2;
            _x -= AppSettings.BlockSizeU * ORoot.ScreenUnit / 2;

            _chunkImage = surface.Snapshot();

            surface.Dispose();
        }
예제 #4
0
        public void OnDrawFrame(IGL10 gl)
        {
            GLES20.GlClear(GLES20.GlColorBufferBit | GLES20.GlDepthBufferBit | GLES20.GlStencilBufferBit);

            // create the contexts if not done already
            if (context == null)
            {
                var glInterface = GRGlInterface.CreateNativeGlInterface();
                context = GRContext.Create(GRBackend.OpenGL, glInterface);
            }

            // manage the drawing surface
            if (renderTarget == null || surface == null || renderTarget.Width != surfaceWidth || renderTarget.Height != surfaceHeight)
            {
                // create or update the dimensions
                renderTarget?.Dispose();
                var buffer = new int[3];
                GLES20.GlGetIntegerv(GLES20.GlFramebufferBinding, buffer, 0);
                GLES20.GlGetIntegerv(GLES20.GlStencilBits, buffer, 1);
                GLES20.GlGetIntegerv(GLES20.GlSamples, buffer, 2);
                var samples    = buffer[2];
                var maxSamples = context.GetMaxSurfaceSampleCount(colorType);
                if (samples > maxSamples)
                {
                    samples = maxSamples;
                }
                var glInfo = new GRGlFramebufferInfo((uint)buffer[0], colorType.ToGlSizedFormat());
                renderTarget = new GRBackendRenderTarget(surfaceWidth, surfaceHeight, samples, buffer[1], glInfo);

                // create the surface
                surface?.Dispose();
                surface = SKSurface.Create(context, renderTarget, surfaceOrigin, colorType);
            }

            using (new SKAutoCanvasRestore(surface.Canvas, true))
            {
                // start drawing
                var e = new SKPaintGLSurfaceEventArgs(surface, renderTarget, surfaceOrigin, colorType);
                OnPaintSurface(e);
#pragma warning disable CS0618 // Type or member is obsolete
                OnDrawFrame(e.Surface, e.RenderTarget);
#pragma warning restore CS0618 // Type or member is obsolete
            }

            // flush the SkiaSharp contents to GL
            surface.Canvas.Flush();
            context.Flush();
        }
예제 #5
0
        protected override bool OnDrawn(Cairo.Context cr)
        {
            int width, height;

            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
            {
                this.Log().Trace($"Render {renderCount++}");
            }

            var dpi = (Window.Screen?.Resolution ?? 1) / 96.0;

            width  = (int)AllocatedWidth;
            height = (int)AllocatedHeight;

            var scaledWidth  = (int)(width * dpi);
            var scaledHeight = (int)(height * dpi);

            var info = new SKImageInfo(scaledWidth, scaledHeight, SKImageInfo.PlatformColorType, SKAlphaType.Premul);

            // reset the bitmap if the size has changed
            if (bitmap == null || info.Width != bitmap.Width || info.Height != bitmap.Height)
            {
                bitmap = new SKBitmap(scaledWidth, scaledHeight, SKColorType.Rgba8888, SKAlphaType.Premul);
            }

            using (var surface = SKSurface.Create(info, bitmap.GetPixels(out _)))
            {
                surface.Canvas.Clear(SKColors.White);

                surface.Canvas.Scale((float)dpi);

                WUX.Window.Current.Compositor.Render(surface, info);

                using (var gtkSurface = new Cairo.ImageSurface(
                           bitmap.GetPixels(out _),
                           Cairo.Format.Argb32,
                           bitmap.Width, bitmap.Height,
                           bitmap.Width * 4))
                {
                    gtkSurface.MarkDirty();
                    cr.Scale(1 / dpi, 1 / dpi);
                    cr.SetSourceSurface(gtkSurface, 0, 0);
                    cr.Paint();
                }
            }

            return(true);
        }
예제 #6
0
        static async Task <(string?contentType, byte[] body)> HandleImageAsync(string status, string id)
        {
            using var response = await _http.GetAsync($"https://shinycolors.enza.fun/assets/{id}");

            if (!response.IsSuccessStatusCode)
            {
                return(null, Array.Empty <byte>());
            }

            var contentType = response.Headers.FirstOrDefault(x => x.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? "";
            var tokens      = status.Split('_');

            using var body = await response.Content.ReadAsStreamAsync();

            using var memory = new MemoryStream();

            await body.CopyToAsync(memory);

            body.Close();

            /* */ var bytes = memory.ToArray();

            memory.Close();

            using var bitmap = SKBitmap.Decode(bytes);

            if (bitmap is null)
            {
                return(contentType, bytes);
            }

            using var surface = SKSurface.Create(new SKImageInfo(bitmap.Width, bitmap.Height));

            if (surface is null)
            {
                return(contentType, bytes);
            }

            using var canvas = surface.Canvas;

            if ( // Background
                bitmap.Width == 1136 &&
                bitmap.Height == 640 ||
                bitmap.Width == 1136 &&
                bitmap.Height == 1280)
            {
                if ( // JFIF (JPEG)
                    bytes.AsSpan().StartsWith(stackalloc byte[] { 0xff, 0xd8, 0xff, 0xe0 }))
예제 #7
0
        public void SnapshotWithDifferentBoundsReturnsDifferentInstance()
        {
            var info = new SKImageInfo(100, 100);

            using var surface = SKSurface.Create(info);
            Assert.NotNull(surface);

            var image1 = surface.Snapshot(new SKRectI(10, 20, 90, 90));

            Assert.NotNull(image1);
            var image2 = surface.Snapshot(new SKRectI(10, 10, 80, 90));

            Assert.NotNull(image2);

            Assert.NotEqual(image1, image2);
        }
예제 #8
0
        public void SnapshotWithBoundsReturnsSameInstance()
        {
            var info = new SKImageInfo(100, 100);

            using var surface = SKSurface.Create(info);
            Assert.NotNull(surface);

            var image1 = surface.Snapshot();

            Assert.NotNull(image1);
            var image2 = surface.Snapshot(info.Rect);

            Assert.NotNull(image2);

            Assert.Equal(image1, image2);
        }
        public static SKImage ApplyErode(SKImage image, int degree)
        {
            var skErode   = SKImageFilter.CreateErode(degree, degree);
            var skSurface = SKSurface.Create(new SKImageInfo(100, 100));
            var skCanvas  = skSurface.Canvas;
            var Paint     = new SKPaint();

            Paint.ImageFilter = skErode;
            skCanvas.Clear();
            skCanvas.DrawImage(image, 0, 0, Paint);
            var img = skSurface.Snapshot();

            skCanvas.Dispose();
            skSurface.Dispose();
            return(img);
        }
예제 #10
0
 public override void Draw()
 {
     bmp.Lock();
     using (var surface = SKSurface.Create(
                width: Width,
                height: Height,
                colorType: SKColorType.Bgra8888,
                alphaType: SKAlphaType.Premul,
                pixels: bmp.BackBuffer,
                rowBytes: Width * 4))
     {
         Draw(surface);
     }
     bmp.AddDirtyRect(new Int32Rect(0, 0, Width, Height));
     bmp.Unlock();
 }
예제 #11
0
        private void DrawBitmap(Action <SKSurface, BitmapData> draw)
        {
            using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
            {
                var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bitmap.PixelFormat);

                using (var surface = SKSurface.Create(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul, data.Scan0, data.Stride))
                {
                    Assert.NotNull(surface);

                    draw(surface, data);
                }

                bitmap.UnlockBits(data);
            }
        }
예제 #12
0
        public void DrawText(float x = 0, float y = 0, string text = "", int size = 24, string font = "Arial", string color = "#ff000000")
        {
            using (var surface = SKSurface.Create(new SKImageInfo(Context.Image.Width, Context.Image.Height)))
                using (var canvas = surface.Canvas)
                    using (var paint = new SKPaint()
                    {
                        TextSize = size, IsAntialias = true, Color = SKColor.Parse(color)
                    })
                    {
                        canvas.DrawBitmap(Context.Image, 0, 0);
                        canvas.DrawText(text, Context.Image.Width * x, Context.Image.Height * y, new SKFont(SKTypeface.FromFamilyName(font)), paint);
                        canvas.Flush();

                        Context.Image = SKBitmap.FromImage(surface.Snapshot());
                    }
        }
예제 #13
0
        private Task <UIImage> RenderPinAsync(SKPin pin, CancellationToken token = default(CancellationToken))
        {
            return(Task.Run(() =>
            {
                double bitmapWidth = pin.Width * _screenDensity;
                double bitmapHeight = pin.Height * _screenDensity;

                using (SKSurface surface = SKSurface.Create((int)bitmapWidth, (int)bitmapHeight, SKColorType.Rgba8888, SKAlphaType.Premul))
                {
                    surface.Canvas.Clear(SKColor.Empty);
                    pin.DrawPin(surface);

                    return surface.PeekPixels().ToUIImage();
                }
            }, token));
        }
예제 #14
0
        public void OnDrawFrame(IGL10 gl)
        {
            GLES10.GlClear(GLES10.GlStencilBufferBit);

            // create the surface
            using (var surface = SKSurface.Create(context, renderTarget))
            {
                // draw using SkiaSharp
                OnDrawFrame(surface, renderTarget);

                surface.Canvas.Flush();
            }

            // flush the SkiaSharp contents to GL
            context.Flush();
        }
예제 #15
0
        public void SimpleSurfaceWithPropertiesIsCorrect()
        {
            var info  = new SKImageInfo(100, 100);
            var props = new SKSurfaceProperties(SKSurfacePropsFlags.UseDeviceIndependentFonts, SKPixelGeometry.RgbVertical);

            using (var surface = SKSurface.Create(info, props))
            {
                Assert.NotNull(surface);

                Assert.Equal(SKPixelGeometry.RgbVertical, surface.SurfaceProperties.PixelGeometry);
                Assert.Equal(SKSurfacePropsFlags.UseDeviceIndependentFonts, surface.SurfaceProperties.Flags);

                Assert.Equal(props.PixelGeometry, surface.SurfaceProperties.PixelGeometry);
                Assert.Equal(props.Flags, surface.SurfaceProperties.Flags);
            }
        }
        private SKSurface RasterizeSegment(SKPicture segment, RasterizeDimensions dim, float skewAngle, params SKPaint[] paints)
        {
            if (dim.SvgWidth <= 0 || dim.SvgWidth <= 0)
            {
                return(null);
            }
            var surface = SKSurface.Create(dim.SvgInfo);

            surface.Canvas.Translate(dim.Translate.X, dim.Translate.Y);
            Skew(surface.Canvas, skewAngle, 0);
            foreach (var paint in paints)
            {
                surface.Canvas.DrawPicture(segment, ref dim.SvgMatrix, paint);
            }
            return(surface);
        }
예제 #17
0
        protected override void OnResize(ResizeEventArgs e)
        {
            GL.Viewport(0, 0, e.Width, e.Height);
            _surface?.Dispose();
            _surface = null;
            var fbo          = GL.GetInteger(GetPName.FramebufferBinding);
            var stencilDepth = GL.GetInteger((GetPName)0x0D57);
            var samples      = GL.GetInteger((GetPName)0x80A9);
            var target       = new GRBackendRenderTarget(e.Width, e.Height,
                                                         samples, stencilDepth, new GRGlFramebufferInfo((uint)fbo, GRPixelConfig.Rgba8888.ToGlSizedFormat()));

            _surface = SKSurface.Create(GrContext, target, GRSurfaceOrigin.TopLeft,
                                        GRPixelConfig.Rgba8888.ToColorType());
            Canvas = _surface.Canvas;
            base.OnResize(e);
        }
예제 #18
0
 public RoomData(string id)
 {
     RoomId    = id;
     ImageInfo = new SKImageInfo(800, 600);
     Image     = SKImage.Create(new SKImageInfo(800, 600));
     Surface   = SKSurface.Create(ImageInfo);
     Paint     = new SKPaint
     {
         IsAntialias = true,
         Color       = new SKColor(0, 0, 0, 255),
         StrokeWidth = 4,
         PathEffect  = SKPathEffect.CreateCorner(50),
         Style       = SKPaintStyle.Stroke
     };
     Path = new SKPath();
 }
예제 #19
0
        public void GpuSurfaceIsCreated()
        {
            using (var ctx = CreateGlContext()) {
                ctx.MakeCurrent();

                using (var grContext = GRContext.Create(GRBackend.OpenGL))
                    using (var surface = SKSurface.Create(grContext, true, new SKImageInfo(100, 100))) {
                        Assert.NotNull(surface);

                        var canvas = surface.Canvas;
                        Assert.NotNull(canvas);

                        canvas.Clear(SKColors.Transparent);
                    }
            }
        }
예제 #20
0
        public ISkiaGpuRenderSession BeginRenderingSession()
        {
            var  glSession = _surface.BeginDraw();
            bool success   = false;

            try
            {
                var disp = glSession.Context;
                var gl   = disp.GlInterface;
                gl.GetIntegerv(GL_FRAMEBUFFER_BINDING, out var fb);

                var size    = glSession.Size;
                var scaling = glSession.Scaling;
                if (size.Width <= 0 || size.Height <= 0 || scaling < 0)
                {
                    glSession.Dispose();
                    throw new InvalidOperationException(
                              $"Can't create drawing context for surface with {size} size and {scaling} scaling");
                }

                gl.Viewport(0, 0, size.Width, size.Height);
                gl.ClearStencil(0);
                gl.ClearColor(0, 0, 0, 0);
                gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
                lock (_grContext)
                {
                    _grContext.ResetContext();

                    var renderTarget =
                        new GRBackendRenderTarget(size.Width, size.Height, disp.SampleCount, disp.StencilSize,
                                                  new GRGlFramebufferInfo((uint)fb, GRPixelConfig.Rgba8888.ToGlSizedFormat()));
                    var surface = SKSurface.Create(_grContext, renderTarget,
                                                   glSession.IsYFlipped ? GRSurfaceOrigin.TopLeft : GRSurfaceOrigin.BottomLeft,
                                                   GRPixelConfig.Rgba8888.ToColorType());

                    success = true;
                    return(new GlGpuSession(_grContext, renderTarget, surface, glSession));
                }
            }
            finally
            {
                if (!success)
                {
                    glSession.Dispose();
                }
            }
        }
예제 #21
0
        static void UpdateViewContent(FormRenderUpdateEventArgs formRenderUpdateEventArgs)
        {
            needUpdateContent = false;
            //1. create platform bitmap
            // create the surface
            int w = 800;
            int h = 600;

            if (myImg == null)
            {
                myImg = new TestGlfw.MyNativeRGBA32BitsImage(w, h);
            }


            int testNo = 2;

            if (testNo == 0)
            {
                //test1
                // create the surface
                var info = new SKImageInfo(w, h, SKImageInfo.PlatformColorType, SKAlphaType.Premul);
                using (var surface = SKSurface.Create(info, myImg.Scan0, myImg.Stride))
                {
                    // start drawing
                    SKCanvas canvas = surface.Canvas;
                    DrawWithSkia(canvas);
                    surface.Canvas.Flush();
                }
                glBmp = new PixelFarm.DrawingGL.GLBitmap(w, h, myImg.Scan0);
            }
            else
            {
                ////---------------------------------------------------------------------------------------
                //test2
                var lionShape = new PixelFarm.Agg.SpriteShape();
                lionShape.ParseLion();
                var lionBounds = lionShape.Bounds;
                //-------------
                var aggImage   = new PixelFarm.Agg.ActualImage((int)lionBounds.Width, (int)lionBounds.Height, PixelFarm.Agg.PixelFormat.ARGB32);
                var imgGfx2d   = new PixelFarm.Agg.ImageGraphics2D(aggImage);
                var aggPainter = new PixelFarm.Agg.AggCanvasPainter(imgGfx2d);

                DrawLion(aggPainter, lionShape, lionShape.Path.Vxs);
                //convert affImage to texture
                glBmp = LoadTexture(aggImage);
            }
        }
예제 #22
0
        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="fontpath">指定的字体路径</param>
        /// <param name="text">指定的文字内容</param>
        /// <returns></returns>
        public static byte[] CreateImage(string fontpath, string text, float font_size = 100)
        {
            //支持文字多行
            List <string> list = text.Split('\n').ToList();

            list.RemoveAll(x => { return(string.IsNullOrEmpty(x.Trim())); }); //删除空行
            list.Reverse();                                                   //顺序反转
            float line_height = 1.5F;                                         //行距
            float height      = 480;

            if (list.Count * line_height * font_size >= height)
            {
                height = list.Count * line_height * font_size;
            }
            var info = new SKImageInfo(1100, (int)height);

            using (var surface = SKSurface.Create(info))
            {
                var canvas = surface.Canvas;
                // make sure the canvas is blank
                canvas.Clear(SKColors.White);

                var paint = new SKPaint
                {
                    Color       = SKColors.Black,
                    IsAntialias = true,
                    Style       = SKPaintStyle.Fill,
                    TextAlign   = SKTextAlign.Center,
                    TextSize    = font_size,
                    Typeface    = SkiaSharp.SKTypeface.FromFile(fontpath, 0)
                };

                int i = 0;
                list.ForEach(x =>
                {
                    var coord = new SKPoint(info.Width / 2, (info.Height + paint.TextSize * (list.Count - i) - paint.TextSize * i * 1.5F) / 2);
                    canvas.DrawText(x.Trim(), coord, paint);
                    i++;
                });

                using (var image = surface.Snapshot())
                    using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        return(data.ToArray());
                    }
            }
        }
예제 #23
0
        private void DoInvalidate()
        {
            if (designMode)
            {
                return;
            }

            if (!isVisible)
            {
                return;
            }

            if (ActualWidth <= 0 || ActualHeight <= 0)
            {
                CanvasSize = SKSize.Empty;
                return;
            }

            var info = CreateBitmap(out var unscaledSize, out var dpi);

            using (var surface = SKSurface.Create(info, pixelsHandle.AddrOfPinnedObject(), info.RowBytes))
            {
                var userVisibleSize = IgnorePixelScaling ? unscaledSize : info.Size;
                CanvasSize = userVisibleSize;

                if (IgnorePixelScaling)
                {
                    var canvas = surface.Canvas;
                    canvas.Scale(dpi);
                    canvas.Save();
                }

                OnPaintSurface(new SKPaintSurfaceEventArgs(surface, info.WithSize(userVisibleSize), info));
            }

            // This implementation is not fast enough, and providing the original pixel buffer
            // is needed, yet the internal `IBufferByteAccess` interface is not yet available in Uno.
            // Once it is, we can replace this implementation and provide the pinned array directly
            // to skia.
            using (var data = bitmap.PixelBuffer.AsStream())
            {
                data.Write(pixels, 0, pixels.Length);
                data.Flush();
            }

            bitmap.Invalidate();
        }
예제 #24
0
        protected override HandleRef BuildWindowCore(HandleRef hwndParent)
        {
            var wndclass = new User32.WNDCLASSEX();

            wndclass.cbSize    = Marshal.SizeOf <User32.WNDCLASSEX>();
            wndclass.style     = 0;
            wndclass.hInstance = Kernel32.GetModuleHandle(null).DangerousGetHandle();
            User32.RegisterClassEx(ref wndclass);
            var windowHandle = User32.CreateWindowEx((User32.WindowStylesEx)WS_EX_NOREDIRECTIONBITMAP, "static", "", User32.WindowStyles.WS_CHILD | User32.WindowStyles.WS_CLIPCHILDREN | User32.WindowStyles.WS_VISIBLE, 0, 0, (int)Width, (int)Height, hwndParent.Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            User32.SetWindowPos(windowHandle, hwndParent.Handle, 0, 0, (int)Width, (int)Height, User32.SetWindowPosFlags.SWP_SHOWWINDOW);
            ANGLE.InitializeContext((int)Width, (int)Height, true, windowHandle, User32.GetDC(windowHandle).DangerousGetHandle());
            var angleInterface = GRGlInterface.CreateAngle(ANGLE.AngleGetProcAddress);
            var grContext      = GRContext.CreateGl(angleInterface);
            var buffer         = ANGLE.GetFrameBuffer();
            var fbinfo         = new GRGlFramebufferInfo(buffer, ANGLE.GetFramebufferFormat());
            var backendRT      = new GRBackendRenderTarget((int)Width, (int)Height, 4, 8, fbinfo);
            var surfaceprops   = new SKSurfaceProperties(SKSurfacePropsFlags.UseDeviceIndependentFonts, SKPixelGeometry.Unknown);
            var surface        = SKSurface.Create(grContext, backendRT, GRSurfaceOrigin.BottomLeft, SKColorType.Rgba8888, null, surfaceprops);
            var canvas         = surface.Canvas;

            canvas.Clear(SKColor.Empty);
            SKPaint paint = new SKPaint();

            paint.Style       = SKPaintStyle.Fill;
            paint.IsAntialias = true;
            paint.StrokeWidth = 4;
            paint.Color       = new SKColor(0xff4285f4);
            SKRect rect = SKRect.Create(10, 10, 100, 160);

            canvas.DrawRect(rect, paint);
            SKRoundRect oval = new SKRoundRect();

            oval.SetOval(rect);
            oval.Offset(40, 80);
            paint.Color = new SKColor(0xffdb4437);
            canvas.DrawRoundRect(oval, paint);
            paint.Color = new SKColor(0xff0f9d58);
            canvas.DrawCircle(180, 50, 25, paint);
            rect.Offset(80, 50);
            paint.Color = new SKColor(0xfff4b400);
            paint.Style = SKPaintStyle.Stroke;
            canvas.DrawRoundRect(rect, 10, 10, paint);
            canvas.Flush();
            ANGLE.Swap();
            return(new HandleRef(this, windowHandle));
        }
        public Stream Assemble()
        {
            // # Set the number of frames per second to display
            // frameRate( frame_rate )

            //SKCanvas canvas = new SKCanvas()
            SKPath  path    = new SKPath();
            Stream  stream  = null;
            SKImage skImage = null;

            try {
                using (var skSurface = SKSurface.Create(new SKImageInfo(w, h))) {
                    var canvas = skSurface.Canvas;
                    // # Sets color space to Hue Saturation Brightness with max values of HSB respectively
                    // colorMode(HSB, 360, 100, 100, 100)

                    //background(0, 0, 100)
                    canvas.Clear(SKColors.White);
                    // rectMode(CORNER)

                    // draw ...
                    draw(canvas);

                    canvas.Flush();

                    //skImage = skSurface.Snapshot();
                    SKPaint paintConvert = SkiaSharpUtility.CreateDefaultPaint();
                    //skImage = SkiaSharpUtility.ScaleSurfaceToImage( skSurface, ImageCanvasSize, size, paintConvert );
                    skImage = skSurface.Snapshot();
                }
                // encode
                SKData skData = SkiaSharpUtility.EncodeImageToSKData(skImage, "png");

                stream = skData.AsStream();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
            finally {
                if (skImage != null)
                {
                    skImage.Dispose();
                }
                paint.Dispose();
            }
            return(stream);
        }
예제 #26
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            int    width, height;
            double dpiX = 1.0;
            double dpiY = 1.0;

            if (IgnorePixelScaling)
            {
                width  = (int)ActualWidth;
                height = (int)ActualHeight;
            }
            else
            {
                var m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
                dpiX   = m.M11;
                dpiY   = m.M22;
                width  = (int)(ActualWidth * dpiX);
                height = (int)(ActualHeight * dpiY);
            }

            var info = new SKImageInfo(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul);

            // reset the bitmap if the size has changed
            if (bitmap == null || info.Width != bitmap.PixelWidth || info.Height != bitmap.PixelHeight)
            {
                bitmap = new WriteableBitmap(width, height, dpiX, dpiY, PixelFormats.Pbgra32, null);
            }

            // draw on the bitmap
            bitmap.Lock();
            using (var surface = SKSurface.Create(info, bitmap.BackBuffer, bitmap.BackBufferStride))
            {
                if (fsurface != null)
                {
                    fsurface.UpdateSurface(surface);
                }
                OnPaintSurface(new SKPaintSurfaceEventArgs(surface, info));
                surface.Canvas.Flush();
            }

            // draw the bitmap to the screen
            bitmap.AddDirtyRect(new Int32Rect(0, 0, width, height));
            bitmap.Unlock();
            drawingContext.DrawImage(bitmap, new Rect(0, 0, ActualWidth, ActualHeight));
        }
예제 #27
0
        async Task <byte[]?> ITileSource.GetTileAsync(int x, int y, int z)
        {
            if (rasterProperties == null)
            {
                throw new InvalidOperationException("rasterProperties property is null.");
            }

            if (String.IsNullOrEmpty(this.configuration.ContentType))
            {
                throw new InvalidOperationException("configuration.ContentType property is null.");
            }

            if ((z < this.configuration.MinZoom) || (z > this.configuration.MaxZoom))
            {
                return(null);
            }
            else
            {
                var tileBounds      = U.WebMercator.GetTileBounds(x, U.WebMercator.FlipYCoordinate(y, z), z);
                var tileCoordinates = BuildTileCoordinatesList(this.rasterProperties, tileBounds);
                if (tileCoordinates.Count == 0)
                {
                    return(null);
                }

                var width  = U.WebMercator.TileSize;
                var height = U.WebMercator.TileSize;

                var imageInfo = new SKImageInfo(
                    width: width,
                    height: height,
                    colorType: SKColorType.Rgba8888,
                    alphaType: SKAlphaType.Premul);

                using var surface = SKSurface.Create(imageInfo);
                using var canvas  = surface.Canvas;
                canvas.Clear(new SKColor(0));

                DrawGeoTiffTilesToRasterCanvas(canvas, width, width, tileBounds, tileCoordinates, 0, this.rasterProperties.TileWidth, this.rasterProperties.TileHeight);

                var imageFormat = U.ImageHelper.SKEncodedImageFormatFromMediaType(this.configuration.ContentType);
                using SKImage image = surface.Snapshot();
                using SKData data   = image.Encode(imageFormat, 90); // TODO: pass quality parameter

                return(await Task.FromResult(data.ToArray()));
            }
        }
예제 #28
0
        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);
        }
예제 #29
0
        public override void Draw(CGRect rect)
        {
            base.Draw(rect);

            var screenScale = UIScreen.MainScreen.Scale;
            var width       = (int)(Bounds.Width * screenScale);
            var height      = (int)(Bounds.Height * screenScale);

            if (_buff == IntPtr.Zero || width != _bufferWidth || height != _bufferHeight)
            {
                if (_buff != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(_buff);
                }

                _buff = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(width * height * 4);

                _bufferWidth  = width;
                _bufferHeight = height;

                (_mycoContainer as IMycoController).SendSurfaceSize(width, height);
            }

            using (var surface = SKSurface.Create(width, height, SKColorType.N_32, SKAlphaType.Premul, _buff, width * 4))
            {
                var skcanvas = surface.Canvas;

                skcanvas.Clear();
                skcanvas.Scale((float)screenScale, (float)screenScale);
                using (new SKAutoCanvasRestore(skcanvas, true))
                {
                    (_mycoContainer as IMycoController).SendDraw(skcanvas);
                }
            }

            using (var colorSpace = CGColorSpace.CreateDeviceRGB())
                using (var bContext = new CGBitmapContext(_buff, width, height, 8, width * 4, colorSpace, (CGImageAlphaInfo)BitmapInfo))
                    using (var image = bContext.ToImage())
                        using (var context = UIGraphics.GetCurrentContext())
                        {
                            // flip the image for CGContext.DrawImage
                            context.TranslateCTM(0, Frame.Height);
                            context.ScaleCTM(1, -1);
                            context.DrawImage(Bounds, image);
                        }
        }
예제 #30
0
        private byte[] RenderPage(Element element, Size size)
        {
            // scale the result so it is more readable
            const float scalingFactor = 2;

            var imageInfo = new SKImageInfo((int)(size.Width * scalingFactor), (int)(size.Height * scalingFactor));

            using var surface = SKSurface.Create(imageInfo);
            surface.Canvas.Scale(scalingFactor);

            var canvas = new Canvas(surface.Canvas);

            element?.Draw(canvas, size);

            surface.Canvas.Save();
            return(surface.Snapshot().Encode(SKEncodedImageFormat.Png, 100).ToArray());
        }