コード例 #1
0
        /// <summary>
        /// Renders the specified matrix.
        /// </summary>
        /// <param name="matrix">The matrix.</param>
        /// <param name="format">The format.</param>
        /// <param name="content">The content.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public SKBitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
        {
            var width         = matrix.Width;
            var height        = matrix.Height;
            var font          = TextFont ?? DefaultTextFont;
            var emptyArea     = 0;
            var outputContent = font != null &&
                                (options == null || !options.PureBarcode) &&
                                !String.IsNullOrEmpty(content) &&
                                (format == BarcodeFormat.CODE_39 ||
                                 format == BarcodeFormat.CODE_93 ||
                                 format == BarcodeFormat.CODE_128 ||
                                 format == BarcodeFormat.EAN_13 ||
                                 format == BarcodeFormat.EAN_8 ||
                                 format == BarcodeFormat.CODABAR ||
                                 format == BarcodeFormat.ITF ||
                                 format == BarcodeFormat.UPC_A ||
                                 format == BarcodeFormat.UPC_E ||
                                 format == BarcodeFormat.MSI ||
                                 format == BarcodeFormat.PLESSEY);

            if (options != null)
            {
                if (options.Width > width)
                {
                    width = options.Width;
                }
                if (options.Height > height)
                {
                    height = options.Height;
                }
            }

            // calculating the scaling factor
            var pixelsizeWidth  = width / matrix.Width;
            var pixelsizeHeight = height / matrix.Height;

            SKBitmap bitmap     = new SKBitmap(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
            IntPtr   pixelsAddr = bitmap.GetPixels();

            unsafe
            {
                var ptr            = (uint *)pixelsAddr.ToPointer();
                var forecolor      = (uint)Foreground;
                var backcolor      = (uint)Background;
                var textAreaHeight = (int)(TextSize < 1 ? 10 : TextSize);

                emptyArea = outputContent && height > textAreaHeight ? textAreaHeight : 0;

                for (int y = 0; y < matrix.Height - emptyArea; y++)
                {
                    // stretching the line by the scaling factor
                    for (var pixelsizeHeightProcessed = 0;
                         pixelsizeHeightProcessed < pixelsizeHeight;
                         pixelsizeHeightProcessed++)
                    {
                        // going through the columns of the current line
                        for (var x = 0; x < matrix.Width; x++)
                        {
                            var color = matrix[x, y] ? forecolor : backcolor;
                            // stretching the columns by the scaling factor
                            for (var pixelsizeWidthProcessed = 0;
                                 pixelsizeWidthProcessed < pixelsizeWidth;
                                 pixelsizeWidthProcessed++)
                            {
                                *ptr++ = color;
                            }
                        }
                        // fill up to the right if the barcode doesn't fully fit in
                        for (var x = pixelsizeWidth * matrix.Width; x < width; x++)
                        {
                            *ptr++ = backcolor;
                        }
                    }
                }
                // fill up to the bottom if the barcode doesn't fully fit in
                for (var y = pixelsizeHeight * matrix.Height; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        *ptr++ = backcolor;
                    }
                }
                // fill the bottom area with the background color if the content should be written below the barcode
                if (outputContent)
                {
                    if (emptyArea > 0)
                    {
                        for (int y = height - emptyArea; y < height; y++)
                        {
                            for (var x = 0; x < width; x++)
                            {
                                *ptr++ = backcolor;
                            }
                        }
                    }
                }
            }

            if (emptyArea > 0)
            {
                //using (var surface = SKSurface.Create(width, height, SKImageInfo.PlatformColorType, SKAlphaType.Premul))
                using (SKCanvas myCanvas = new SKCanvas(bitmap))
                    using (var paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = Foreground;
                        paint.Typeface    = font;
                        paint.TextSize    = TextSize < 1 ? 10 : TextSize;

                        // output content text below the barcode
                        if (emptyArea > 0)
                        {
                            switch (format)
                            {
                            case BarcodeFormat.UPC_E:
                            case BarcodeFormat.EAN_8:
                                if (content.Length < 8)
                                {
                                    content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                                }
                                if (content.Length > 4)
                                {
                                    content = content.Insert(4, "   ");
                                }
                                break;

                            case BarcodeFormat.EAN_13:
                                if (content.Length < 13)
                                {
                                    content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                                }
                                if (content.Length > 7)
                                {
                                    content = content.Insert(7, "   ");
                                }
                                if (content.Length > 1)
                                {
                                    content = content.Insert(1, "   ");
                                }
                                break;

                            case BarcodeFormat.UPC_A:
                                if (content.Length < 12)
                                {
                                    content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
                                }
                                if (content.Length > 11)
                                {
                                    content = content.Insert(11, "   ");
                                }
                                if (content.Length > 6)
                                {
                                    content = content.Insert(6, "   ");
                                }
                                if (content.Length > 1)
                                {
                                    content = content.Insert(1, "   ");
                                }
                                break;
                            }
                            var textWidth = paint.MeasureText(content);
                            var x         = (pixelsizeWidth * matrix.Width - textWidth) / 2;
                            var y         = height - 1;
                            x = x < 0 ? 0 : x;
                            myCanvas.DrawText(content, x, y, paint);
                        }
                        myCanvas.Flush();
                    }
            }

            return(bitmap);
        }
コード例 #2
0
ファイル: SvgImage.cs プロジェクト: alexandrvslv/pdf-clown
 public static void DrawImage(SKCanvas canvas, string imageName, SKColor color, SKRect bounds, float indent = 2)
 {
     DrawImage(canvas, typeof(SvgImage).Assembly, imageName, color, bounds, indent);
 }
コード例 #3
0
        private void VolumeDisplay_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            int h     = info.Height;
            int w     = info.Width;
            int bound = status.RecentVolumMeasurements.Capacity() - 1;

            float wIncr   = w / status.RecentVolumMeasurements.Capacity();
            float thisMax = 0;

            float startVal = status.RecentVolumMeasurements.Get(0);

            if (startVal > thisMax)
            {
                thisMax = startVal;
            }
            float startY = startVal / (MaxVol * 1.1F);

            startY = h - (startY * h);
            float startX = w;

            for (int i = 0; i < bound; i++)
            {
                float endX = startX - wIncr;

                float endVal = status.RecentVolumMeasurements.Get(i + 1);
                if (endVal > thisMax)
                {
                    thisMax = endVal;
                }

                float endY = endVal / (MaxVol * 1.1F);
                endY = h - (endY * h);

                canvas.DrawLine(startX, startY - 5, endX, endY - 5, VolPaint);

                startX = endX;
                startY = endY;
            }
            canvas.RotateDegrees(-90);
            canvas.DrawText("Volume (L)", new SKPoint(-h / 2, 10), new SKPaint {
                Color = SKColors.Black
            });
            canvas.RotateDegrees(90);
            canvas.DrawText($"{((int)(MaxVol * 10))/10f}", new SKPoint(10, 10), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText("0", new SKPoint(10, h - 10), new SKPaint {
                Color = SKColors.Black
            });

            canvas.DrawText("Time", new SKPoint(w / 2, h), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText("Now", new SKPoint(20, h), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText("Previously", new SKPoint(w - 60, h), new SKPaint {
                Color = SKColors.Black
            });

            canvas.DrawText($"TV: {((int)(status.TV * 100)) / 100f}", new SKPoint(w / 2, 15), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText($"I/E: {((int)(status.IE * 100)) / 100f}", new SKPoint(w / 2, 30), new SKPaint {
                Color = SKColors.Black
            });


            MaxVol = Math.Max(0.25F, (MaxVol + thisMax) / 2);
        }
コード例 #4
0
ファイル: Chart.cs プロジェクト: punker76/Microcharts
 public abstract void DrawContent(SKCanvas canvas, int width, int height);
コード例 #5
0
ファイル: ToolRect.cs プロジェクト: jensbrak/Phiddle
 protected override void DrawTool(SKCanvas c)
 {
     // Draw rect
     c.DrawRect(p0.X, p0.Y, p1.X - p0.X, p1.Y - p0.Y, PaintTool);
 }
コード例 #6
0
        /// <inheritdoc/>
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (inputPath.Length == 0)
            {
                throw new ArgumentException("String can't be empty.", nameof(inputPath));
            }

            if (outputPath.Length == 0)
            {
                throw new ArgumentException("String can't be empty.", nameof(outputPath));
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new InvalidDataException($"Skia unable to read image {inputPath}");
                }

                var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);

                if (!options.CropWhiteSpace &&
                    options.HasDefaultOptions(inputPath, originalImageSize) &&
                    !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = newImageSize.Width;
                var height = newImageSize.Height;

                using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                        using (var outputStream = new SKFileWStream(outputPath))
                            using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
                            {
                                pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                return(outputPath);
                            }
                    }

                    // create bitmap to use for canvas drawing used to draw into bitmap
                    using (var saveBitmap = new SKBitmap(width, height)) // , bitmap.ColorType, bitmap.AlphaType))
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                // create image from resized bitmap to apply blur
                                using (var paint = new SKPaint())
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                if (!double.TryParse(options.ForegroundLayer, out double opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
                                {
                                    pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                }
                            }
                        }
                }
            }

            return(outputPath);
        }
コード例 #7
0
 public virtual void OnDraw(SKCanvas canvas, SKPoint pos, IChartBase chart)
 {
 }
コード例 #8
0
 public void DrawDefaultRectangles(SKCanvas dc, SKRect rect_Card, SKPaint thisPaint)
 {
     MainGraphics !.DrawDefaultRectangles(dc, rect_Card, thisPaint);
 }
コード例 #9
0
        private void ImageSkiaCanvas_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            SKRect imageRect = new SKRect(0, 0, info.Width, info.Height);

            // render out the bitmap
            SKRect outgoingImageRect;

            if (transitionValue >= 1)
            {
                outgoingImageRect = new SKRect(0 - (float)outgoingOffset, 0, info.Width, info.Height);
            }
            else
            {
                outgoingImageRect = new SKRect(0, 0, info.Width, info.Height);
            }


            canvas.DrawBitmap(currentBitmap, outgoingImageRect, BitmapStretch.AspectFill);

            if (transitionValue <= 0)
            {
                return;
            }

            if (RightSwap)
            {
                canvas.DrawBitmap(offscreenBitmap, outgoingImageRect, BitmapStretch.AspectFill);

                // draw our clipping path
                if (offscreenBitmap != null)
                {
                    // animate int the rect that the image is being rendered to
                    int    movementAmount = 600;
                    float  offset         = (float)(movementAmount - (movementAmount * (transitionValue / 2)));
                    SKRect incomingRect   = new SKRect(0, 0, info.Width + offset, info.Height);

                    // draw the faded version of the image
                    using (SKPaint transparentPaint = new SKPaint())
                    {
                        var opacity = Math.Max((transitionValue - .5) * .5, 0);
                        transparentPaint.Color = transparentPaint.Color.WithAlpha((byte)(0xFF * opacity));
                        canvas.DrawBitmap(
                            bitmap: currentBitmap,
                            dest: incomingRect,
                            stretch: BitmapStretch.AspectFill,
                            paint: transparentPaint);
                    }

                    var clipPath = CalculateClipPath(info, transitionValue);
                    canvas.ClipPath(clipPath, SKClipOperation.Intersect);
                    canvas.DrawBitmap(currentBitmap, incomingRect, BitmapStretch.AspectFill);
                }
            }
            else
            {
                // draw our clipping path
                if (offscreenBitmap != null)
                {
                    // animate int the rect that the image is being rendered to
                    int    movementAmount = 600;
                    float  offset         = (float)(movementAmount - (movementAmount * (transitionValue / 2)));
                    SKRect incomingRect   = new SKRect(0, 0, info.Width + offset, info.Height);

                    // draw the faded version of the image
                    using (SKPaint transparentPaint = new SKPaint())
                    {
                        var opacity = Math.Max((transitionValue - .5) * .5, 0);
                        transparentPaint.Color = transparentPaint.Color.WithAlpha((byte)(0xFF * opacity));
                        canvas.DrawBitmap(
                            bitmap: offscreenBitmap,
                            dest: incomingRect,
                            stretch: BitmapStretch.AspectFill,
                            paint: transparentPaint);
                    }

                    var clipPath = CalculateClipPath(info, transitionValue);
                    canvas.ClipPath(clipPath, SKClipOperation.Intersect);
                    canvas.DrawBitmap(offscreenBitmap, incomingRect, BitmapStretch.AspectFill);
                }
            }
        }
コード例 #10
0
ファイル: SkiaEncoder.cs プロジェクト: pnoble04/Emby
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("inputPath");
            }
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException("outputPath");
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new Exception(string.Format("Skia unable to read image {0}", inputPath));
                }

                //_logger.Info("Color type {0}", bitmap.Info.ColorType);

                var originalImageSize = new ImageSize(bitmap.Width, bitmap.Height);
                ImageHelper.SaveImageSize(inputPath, dateModified, originalImageSize);

                if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = Convert.ToInt32(Math.Round(newImageSize.Width));
                var height = Convert.ToInt32(Math.Round(newImageSize.Height));

                using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    var resizeMethod = SKBitmapResizeMethod.Lanczos3;

                    bitmap.Resize(resizedBitmap, resizeMethod);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        using (var outputStream = new SKFileWStream(outputPath))
                        {
                            resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            return(outputPath);
                        }
                    }

                    // create bitmap to use for canvas drawing
                    using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
                    {
                        // create canvas used to draw into bitmap
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                using (var paint = new SKPaint())
                                {
                                    // create image from resized bitmap to apply blur
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                                }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                Double opacity;
                                if (!Double.TryParse(options.ForegroundLayer, out opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (Byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
                            }
                        }
                    }
                }
            }
            return(outputPath);
        }
コード例 #11
0
        public void DrawInfo()
        {
            var teams = Battles.GetScoreInfo().Props.PageProps.Teams;

            teams.Sort(TeamComparer.Comparer);

            var teamsDictionary = new Dictionary <string, List <Team> >();

            foreach (var team in teams)
            {
                if (teamsDictionary.ContainsKey(team.Region))
                {
                    teamsDictionary[team.Region].Add(team);
                }
                else
                {
                    teamsDictionary.Add(team.Region, new List <Team> {
                        team
                    });
                }
            }

            List <BitmapInfo> bitmaps = new List <BitmapInfo>();

            int teamHeight  = 50;
            int offset      = 20;
            int regionWidth = 300 + offset * 2;

            foreach (var region in teamsDictionary)
            {
                int regionHeight = teamHeight * region.Value.Count + 18 + offset * 2;

                /*using (*/
                var bitmap = new SKBitmap(regionWidth, regionHeight);//)
                //{
                using (var c = new SKCanvas(bitmap))
                {
                    using (var path = new SKPath())
                    {
                        path.MoveTo(15, 15);
                        path.LineTo(regionWidth - 10, 10);
                        path.LineTo(regionWidth - 20, regionHeight - 15);
                        path.LineTo(10, regionHeight - 10);
                        path.Close();

                        c.DrawPath(path, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            Color         = SKColors.White,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                        //c.DrawRect(offset, offset, width, height, new SKPaint { Color = SKColors.White });
                    }

                    using (var flag = BitmapFromUrl($"https://teambattles.fortnite.com/image/flag/{region.Value[0].Nationality.ToLower()}.png", region.Value[0].Nationality.ToLower()))
                    {
                        int _x = (regionWidth - flag.Width) / 2;
                        int _y = offset;

                        c.DrawBitmap(flag, _x, _y, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                    }

                    int y = 18 + offset;

                    foreach (var team in region.Value)
                    {
                        c.DrawText(team.Name, 10 + offset, y + 36, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            TextSize      = 20,
                            Typeface      = ChicTypefaces.BurbankBigRegularBlack,
                            Color         = SKColors.Black
                        });

                        using (var paint = new SKPaint
                        {
                            IsAntialias = true,
                            FilterQuality = SKFilterQuality.High,
                            TextSize = 20,
                            Typeface = ChicTypefaces.BurbankBigRegularBlack,
                            Color = SKColors.Black
                        })
                        {
                            c.DrawText($"{team.Score.ToString("N0")}",
                                       regionWidth - 10 - offset - paint.MeasureText($"{team.Score.ToString("N0")}"), y + 36, paint);
                        }

                        y += teamHeight;
                    }
                }

                bitmaps.Add(SaveToCache(bitmap, $"region_{region.Value[0].Nationality}"));
            }

            int maxRegionsPerRow = 7;

            maxRegionsPerRow = Math.Clamp(bitmaps.Count, 0, maxRegionsPerRow);

            int extraHeight   = 800;
            int _regionHeight = bitmaps.Max(bitmap => bitmap.Height);

            int o = 50;

            int width  = maxRegionsPerRow * (regionWidth + o) + o;
            int height = (int)Math.Ceiling((decimal)bitmaps.Count / maxRegionsPerRow) * (_regionHeight + o) + o;

            int extraExtraHeight = (int)(width * 0.5625f) - height - extraHeight;

            extraExtraHeight = extraExtraHeight >= 0 ? extraExtraHeight : 0;
            int extraWidth = (int)((height + extraHeight) * 1.77777777778f) - width;

            extraWidth = extraWidth >= 0 ? extraWidth : 0;

            using (var full = new SKBitmap(width + extraWidth, height + extraHeight + extraExtraHeight))
            {
                using (var c = new SKCanvas(full))
                {
                    using (var paint = new SKPaint
                    {
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High,
                        Shader = SKShader.CreateLinearGradient(new SKPoint(-100, -200), new SKPoint(width + 300, height + 500),
                                                               new SKColor[]
                        {
                            new SKColor(56, 33, 50),
                            new SKColor(192, 4, 92),
                            new SKColor(243, 9, 76),
                            new SKColor(249, 96, 83),
                            new SKColor(250, 111, 84),
                            new SKColor(255, 232, 75),
                            new SKColor(255, 239, 74),
                        }, SKShaderTileMode.Clamp)
                    })
                    {
                        c.DrawRect(0, 0, width + extraWidth, extraHeight, paint);
                    }

                    using (var logo = SKBitmap.Decode($"{Root}Resources/logo.png"))
                    {
                        c.DrawBitmap(logo.Resize(new SKSizeI(logo.Width * 2, logo.Height * 2), SKFilterQuality.High), 100, 25);
                    }

                    using (var lovely = SKBitmap.Decode($"{Root}Resources/hero.webp"))
                    {
                        c.DrawBitmap(lovely, width + extraWidth - lovely.Width, 0);
                    }

                    using (var path = new SKPath())
                    {
                        path.MoveTo(0, 695);
                        path.LineTo((width + extraWidth) / 2, 745);
                        path.LineTo(width + extraWidth - (int)((width + extraWidth) / 1.7f), 715);
                        path.LineTo(width + extraWidth, 790);
                        path.LineTo(width + extraWidth, height + extraHeight);
                        path.LineTo(0, height + extraHeight);
                        path.Close();

                        c.DrawPath(path, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            Color         = SKColors.White,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, -2, 5, 5, SKColors.Black)
                        });
                    }

                    int x = o;
                    int y = o + extraHeight;

                    int xi = 1;

                    foreach (var bmp in bitmaps)
                    {
                        c.DrawBitmap(LoadFromCache(bmp), x, y);

                        if (xi == maxRegionsPerRow)
                        {
                            x  = o;
                            y += _regionHeight + o;
                            xi = 1;
                        }
                        else
                        {
                            x += regionWidth + o;
                            xi++;
                        }
                    }

                    using (var watermark = SKBitmap.Decode($"{Root}Resources/watermark.png"))
                    {
                        c.DrawBitmap(watermark, width - extraWidth - watermark.Width, height + extraHeight - extraExtraHeight - watermark.Height, new SKPaint
                        {
                            IsAntialias   = true,
                            FilterQuality = SKFilterQuality.High,
                            ImageFilter   = SKImageFilter.CreateDropShadow(0, 0, 5, 5, SKColors.Black)
                        });
                    }
                }

                using (var image = SKImage.FromBitmap(full))
                {
                    using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                    {
                        using (var stream = File.OpenWrite($"{Root}Output/output.png"))
                        {
                            data.SaveTo(stream);
                        }
                    }
                }
            }

            TwitterManager.TweetWithMedia($"{Root}Output/output.png", "Fortnite Hearts Wild Team Battles results!\nIt's over guys. Woo");

            foreach (var file in Directory.GetFiles($"{Root}Cache").Where(x => x.Contains("region_")))
            {
                File.Delete(file);
            }

            GC.Collect();
            Console.WriteLine("Done");
        }
コード例 #12
0
        /// <summary>
        /// Create code
        /// </summary>
        /// <returns>image binary</returns>
        public override VerificationCodeValue CreateCode()
        {
            byte[] codeImageBinary = new byte[0];
            string codeString      = CreateCodeString();

            if (!string.IsNullOrWhiteSpace(codeString))
            {
                #region Generate image

                int width  = (fontSize + spaceBetween) * length + 5;
                int height = fontSize + 11;
                using (SKBitmap bitmap = new SKBitmap(width, height))
                {
                    using (SKCanvas canvas = new SKCanvas(bitmap))
                    {
                        canvas.Clear();
                        canvas.DrawColor(new SKColor(backgroundColor.R, backgroundColor.G, backgroundColor.B, backgroundColor.A));
                        using (var paint = new SKPaint())
                        {
                            if (fontColor.HasValue)
                            {
                                var fcolor = fontColor.Value;
                                paint.Color = new SKColor(fcolor.R, fcolor.G, fcolor.B, fcolor.A);
                            }
                            if (!string.IsNullOrWhiteSpace(frontFamilyName))
                            {
                                paint.Typeface = SKTypeface.FromFamilyName(frontFamilyName);
                            }
                            for (int n = 0; n < length; n++)
                            {
                                if (!fontColor.HasValue)
                                {
                                    paint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
                                }
                                paint.TextSize = fontSize;
                                canvas.DrawText(codeString[n].ToString(), n * fontSize + spaceBetween, fontSize, paint);
                            }
                            //interfere line
                            if (interfereColor.HasValue)
                            {
                                var lineColor = interfereColor.Value;
                                paint.Color = new SKColor(lineColor.R, lineColor.G, lineColor.B, lineColor.A);
                            }
                            int linePointHalf = width / 2;
                            for (int i = 0; i < interfereNum; i++)
                            {
                                if (!interfereColor.HasValue)
                                {
                                    paint.Color = new SKColor((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
                                }
                                canvas.DrawLine(random.Next(0, linePointHalf), random.Next(1, height), random.Next(linePointHalf + 1, width), random.Next(1, height), paint);
                            }
                        }
                        using (var image = SKImage.FromBitmap(bitmap))
                        {
                            using (var skdata = image.Encode(SKEncodedImageFormat.Png, 100))
                            {
                                codeImageBinary = skdata.ToArray();
                            }
                        }
                    }
                }

                #endregion
            }

            return(new VerificationCodeValue()
            {
                Code = codeString,
                FileBytes = codeImageBinary
            });
        }
コード例 #13
0
ファイル: ImageLoader.cs プロジェクト: cuiliang/viewer
        private static SKBitmap RotateFlip(SKBitmap bitmap, RotateFlipType rotateFlip)
        {
            var rotationAngle = 0;
            var flipX         = 1;

            switch (rotateFlip)
            {
            case RotateFlipType.RotateNoneFlipNone:
                break;

            case RotateFlipType.Rotate90FlipNone:
                rotationAngle = 90;
                break;

            case RotateFlipType.Rotate180FlipNone:
                rotationAngle = 180;
                break;

            case RotateFlipType.Rotate270FlipNone:
                rotationAngle = 270;
                break;

            case RotateFlipType.RotateNoneFlipX:
                flipX = -1;
                break;

            case RotateFlipType.Rotate90FlipX:
                rotationAngle = 90;
                flipX         = -1;
                break;

            case RotateFlipType.Rotate180FlipX:
                rotationAngle = 180;
                flipX         = -1;
                break;

            case RotateFlipType.Rotate270FlipX:
                rotationAngle = 270;
                flipX         = -1;
                break;
            }

            // don't transform the bitmap if it's not necessary
            if (flipX == 1 && rotationAngle == 0)
            {
                return(bitmap);
            }

            // transform the bitmap according to the rotateFlip value
            using (bitmap)
            {
                var flipDimensions = rotationAngle == 180 || rotationAngle == 0;
                var transformed    = new SKBitmap(
                    flipDimensions ? bitmap.Width : bitmap.Height,
                    flipDimensions ? bitmap.Height : bitmap.Width);
                try
                {
                    using (var surface = new SKCanvas(transformed))
                    {
                        surface.Translate(transformed.Width / 2.0f, transformed.Height / 2.0f);
                        surface.Scale(flipX, 1);
                        surface.RotateDegrees(rotationAngle);
                        surface.Translate(-bitmap.Width / 2.0f, -bitmap.Height / 2.0f);
                        surface.DrawBitmap(bitmap, 0, 0);
                    }
                }
                catch (Exception)
                {
                    transformed.Dispose();
                    throw;
                }

                return(transformed);
            }
        }
コード例 #14
0
ファイル: HUDRenderer.cs プロジェクト: chamons/ArenaLS
 public void Render(SKCanvas canvas, Character c, int x, int y, long frame)
 {
     DrawHUD(canvas, c, x, y);
     DrawCastbar(canvas, x, y, frame);
 }
コード例 #15
0
        private void CreateFeature()
        {
            lock (_sync)
            {
                if (_feature == null)
                {
                    // Create a new one
                    _feature = new Feature
                    {
                        Geometry  = Position.ToMapsui(),
                        ["Label"] = Label,
                    };
                }
                // Check for bitmapId
                if (_bitmapId != -1)
                {
                    // There is already a registered bitmap, so delete it
                    BitmapRegistry.Instance.Unregister(_bitmapId);
                    // We don't have any bitmap up to now
                    _bitmapId = -1;
                }

                Stream stream = null;

                switch (Type)
                {
                case PinType.Svg:
                    // Load the SVG document
                    if (!string.IsNullOrEmpty(Svg))
                    {
                        stream = new MemoryStream(Encoding.UTF8.GetBytes(Svg));
                    }
                    if (stream == null)
                    {
                        return;
                    }
                    _bitmapId = BitmapRegistry.Instance.Register(stream);
                    break;

                case PinType.Pin:
                    // First we have to create a bitmap from Svg code
                    // Create a new SVG object
                    var svg = new SkiaSharp.Extended.Svg.SKSvg();
                    // Load the SVG document
                    stream = Utilities.EmbeddedResourceLoader.Load("Images.Pin.svg", typeof(Pin));
                    if (stream == null)
                    {
                        return;
                    }
                    svg.Load(stream);
                    Width  = svg.CanvasSize.Width * Scale;
                    Height = svg.CanvasSize.Height * Scale;
                    // Create bitmap to hold canvas
                    var info = new SKImageInfo((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height)
                    {
                        AlphaType = SKAlphaType.Premul
                    };
                    var bitmap = new SKBitmap(info);
                    var canvas = new SKCanvas(bitmap);
                    // Now draw Svg image to bitmap
                    using (var paint = new SKPaint())
                    {
                        // Replace color while drawing
                        paint.ColorFilter = SKColorFilter.CreateBlendMode(Color.ToSKColor(), SKBlendMode.SrcIn);     // use the source color
                        canvas.Clear();
                        canvas.DrawPicture(svg.Picture, paint);
                    }
                    // Now convert canvas to bitmap
                    using (var image = SKImage.FromBitmap(bitmap))
                        using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                        {
                            _bitmapData = data.ToArray();
                        }
                    _bitmapId = BitmapRegistry.Instance.Register(new MemoryStream(_bitmapData));
                    break;

                case PinType.Icon:
                    if (Icon != null)
                    {
                        using (var image = SKBitmap.Decode(Icon))
                        {
                            Width     = image.Width * Scale;
                            Height    = image.Height * Scale;
                            _bitmapId = BitmapRegistry.Instance.Register(new MemoryStream(Icon));
                        }
                    }
                    break;
                }

                // If we have a bitmapId (and we should have one), than draw bitmap, otherwise nothing
                if (_bitmapId != -1)
                {
                    // We only want to have one style
                    _feature.Styles.Clear();
                    _feature.Styles.Add(new SymbolStyle
                    {
                        BitmapId       = _bitmapId,
                        SymbolScale    = Scale,
                        SymbolRotation = Rotation,
                        SymbolOffset   = new Offset(Anchor.X, Anchor.Y),
                        Opacity        = 1 - Transparency,
                    });
                }
            }
        }
コード例 #16
0
        public void DrawImage(SKCanvas canvas, SKRect rect_Card)
        {
            SKRect firstRect;
            SKRect secondRect;

            firstRect  = SKRect.Create(2, 2, rect_Card.Width - 6, rect_Card.Height / 2.1f);
            secondRect = SKRect.Create(rect_Card.Width / 4, rect_Card.Height / 2, rect_Card.Width / 2, rect_Card.Height / 2.2f);
            var circleRect = SKRect.Create(2, rect_Card.Height / 2, rect_Card.Width - 4, rect_Card.Height / 2.2f);

            switch (MilkType)
            {
            case EnumMilkType.Strawberry:
                canvas.DrawBitmap(_strawberryImage, firstRect);
                break;

            case EnumMilkType.Chocolate:
                canvas.DrawBitmap(_chocolateImage, firstRect);
                break;

            default:
                throw new BasicBlankException("Must be strawberry or chocolate");
            }
            string thisText = "";

            if (CardCategory != EnumCardCategory.Joker)
            {
                if (CardCategory == EnumCardCategory.Go)
                {
                    thisText = "Go";
                }
                else if (CardCategory == EnumCardCategory.Stop)
                {
                    thisText = "Stop";
                }
                else
                {
                    thisText = Points.ToString();
                }
            }
            switch (CardCategory)
            {
            case EnumCardCategory.Joker:
                var newRect = MainGraphics !.GetActualRectangle(13, 36, 30, 30);
                if (MilkType == EnumMilkType.Chocolate)
                {
                    canvas.DrawSmiley(newRect, _chocolatePaint !, _textBorder !, _blackPaint !);
                }
                else if (MilkType == EnumMilkType.Strawberry)
                {
                    canvas.DrawSmiley(newRect, _redPaint !, _textBorder !, _blackPaint !);
                }
                return;

            case EnumCardCategory.Go:
                canvas.DrawOval(circleRect, _limePaint);
                break;

            case EnumCardCategory.Stop:
                canvas.DrawOval(circleRect, _redPaint);
                break;

            default:
                break;
            }
            if (thisText == "")
            {
                throw new BasicBlankException("No text found");
            }
            var fontSize = secondRect.Height * 1.2f;

            if (thisText == "Stop")
            {
                fontSize = secondRect.Height * .7f; //otherwise parts get cut off.
            }
            var textPaint = MiscHelpers.GetTextPaint(SKColors.White, fontSize);

            canvas.DrawBorderText(thisText, TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, _textBorder !, secondRect);
        }
コード例 #17
0
        public void HelicalWheelBuilderLetter(string aminoAcids, SKCanvas canvas)
        {
            // init. my variables
            var   aminoClass = new AminoAcids();
            var   listAminos = aminoAcids.ToCharArray().ToList();
            float x = 0; float y = 0;
            int   angle     = 270;
            char  lastChar  = '0';
            bool  polarity  = false;
            float xModifier = 0;
            float yModifier = 0;

            HelicalStructure.Clear();
            float modIncrementer = 0;
            float scaleModifier  = 19;
            int   incr           = 1;
            var   percentDiff    = App.ScreenHeight > App.ScreenWidth ? ((App.ScreenHeight / App.ScreenWidth) / ScaleFactor) + WheelEnlarger: ((App.ScreenWidth / App.ScreenHeight) / ScaleFactor) + WheelEnlarger;

            // iterate over the amino acids
            foreach (var item in listAminos)
            {
                // if its a valid character
                if (char.IsLetter(item))
                {
                    // acheck to make sure to add the
                    if (lastChar != '0')
                    {
                        //draw line
                        if (incr < 18)
                        {
                            canvas.DrawLine(x, y, (float)((RADIUS * percentDiff) * Math.Cos(angle * Math.PI / 180F)), (float)((RADIUS * percentDiff) * Math.Sin(angle * Math.PI / 180F)), Line);
                        }
                        // check if polar or not then draw the circle accordingly
                        if (polarity)
                        {
                            canvas.DrawText(lastChar.ToString().ToUpper() + incr, x - (6 * percentDiff), y + (4 * percentDiff), PolarLetters);
                        }
                        else
                        {
                            canvas.DrawText(lastChar.ToString().ToUpper() + incr, x - (6 * percentDiff), y + (4 * percentDiff), NonPolarLetters);
                        }
                        incr += 1;
                    }
                    // determine the x & y coordinates using this formula
                    x = (float)((RADIUS * percentDiff) * Math.Cos(angle * Math.PI / 180F));
                    y = (float)((RADIUS * percentDiff) * Math.Sin(angle * Math.PI / 180F));
                    // add x & y coordinates to my global variable
                    HelicalStructure.Add(new KeyValuePair <string, Point>(item.ToString().ToUpper() + incr, new Point(x, y)));
                    if (incr % scaleModifier == 0)
                    {
                        modIncrementer += 1;
                        scaleModifier   = scaleModifier + 18;
                    }
                    xModifier = x > 0? 13f * modIncrementer * percentDiff : -13f * modIncrementer * percentDiff;
                    yModifier = y > 0? 13f * modIncrementer * percentDiff : -13f * modIncrementer * percentDiff;
                    if (Math.Abs(x) < 5 && modIncrementer > 0)
                    {
                        yModifier = yModifier > 0 ? (yModifier - (.5f * percentDiff)) + (6 * modIncrementer * percentDiff) : (yModifier + (.5f * percentDiff)) - (6 * modIncrementer * percentDiff);
                        xModifier = 0;
                    }
                    x += xModifier;
                    y += yModifier;
                    if (aminoClass.IsAminoAcid(null, item))
                    {
                        if (polarity = aminoClass.IsPolar(null, item))
                        {
                            canvas.DrawCircle(x, y, (AMINORADIUS * percentDiff), PolarAminoAcid);
                        }
                        else
                        {
                            canvas.DrawCircle(x, y, (AMINORADIUS * percentDiff), NonPolarAminoAcid);
                        }
                    }
                    else
                    {
                        canvas.DrawCircle(x, y, (AMINORADIUS * percentDiff), InvalidAminoAcid);
                    }
                    angle += 100;
                    if (angle > 360)
                    {
                        angle -= 360;
                    }
                    lastChar = item;
                }
            }
            if (char.IsLetter(lastChar))
            {
                if (polarity)
                {
                    canvas.DrawText(lastChar.ToString().ToUpper() + incr, x - (6 * percentDiff), y + (4 * percentDiff), PolarLetters);
                }
                else
                {
                    canvas.DrawText(lastChar.ToString().ToUpper() + incr, x - (6 * percentDiff), y + (4 * percentDiff), NonPolarLetters);
                }
            }
        }
コード例 #18
0
ファイル: DrawingContextImpl.cs プロジェクト: vbfool/Perspex
 public DrawingContextImpl(SKCanvas canvas)
 {
     Canvas = canvas;
     Canvas.Clear();
 }
コード例 #19
0
        public void HelicalWheelBuilderThreeLetter(string aminoAcids, SKCanvas canvas)
        {
            var   aminoClass = new AminoAcids();
            var   listAminos = aminoAcids.Split(',').ToList();
            float xval = 0; float yval = 0;
            float xModifier = 0; float yModifier = 0;
            float modIncrementer = 0;
            float scaleModifier  = 19;

            HelicalStructure.Clear();
            int    angle       = 270;
            bool   polarity    = false;
            string lastAmino   = "";
            int    incr        = 1;
            var    percentDiff = App.ScreenHeight > App.ScreenWidth ? ((App.ScreenHeight / App.ScreenWidth) / ScaleFactor) + WheelEnlarger : ((App.ScreenWidth / App.ScreenHeight) / ScaleFactor) + WheelEnlarger;

            foreach (var item in listAminos)
            {
                if (!string.IsNullOrWhiteSpace(item))
                {
                    if (!string.IsNullOrWhiteSpace(lastAmino))
                    {
                        if (incr < 18)
                        {
                            canvas.DrawLine(xval, yval, (float)((RADIUS * percentDiff) * Math.Cos(angle * Math.PI / 180F)), (float)((RADIUS * percentDiff) * Math.Sin(angle * Math.PI / 180F)), Line);
                        }
                        if (polarity)
                        {
                            canvas.DrawText(lastAmino.Substring(0, 1).ToString().ToUpper() + lastAmino.Substring(1, 2) + incr, xval - (7 * percentDiff), yval + (4 * percentDiff), PolarLetters);
                        }
                        else
                        {
                            canvas.DrawText(lastAmino.Substring(0, 1).ToString().ToUpper() + lastAmino.Substring(1, 2) + incr, xval - (7 * percentDiff), yval + (4 * percentDiff), NonPolarLetters);
                        }
                        incr += 1;
                    }
                    xval = (float)((RADIUS * percentDiff) * Math.Cos(angle * Math.PI / 180F));
                    yval = (float)((RADIUS * percentDiff) * Math.Sin(angle * Math.PI / 180F));
                    HelicalStructure.Add(new KeyValuePair <string, Point>(item.Substring(0, 1).ToString().ToUpper() + item.Substring(1, 2) + incr, new Point(xval, yval)));
                    if (incr % scaleModifier == 0)
                    {
                        modIncrementer += 1;
                        scaleModifier   = scaleModifier + 18;
                    }
                    xModifier = xval > 0 ? 13f * modIncrementer * percentDiff : -13f * modIncrementer * percentDiff;
                    yModifier = yval > 0 ? 13f * modIncrementer * percentDiff : -13f * modIncrementer * percentDiff;
                    if (Math.Abs(xval) < 5 && modIncrementer > 0)
                    {
                        yModifier = yModifier > 0 ? (yModifier - (.5f * percentDiff)) + (6 * modIncrementer * percentDiff) : (yModifier + (.5f * percentDiff)) - (6 * modIncrementer * percentDiff);
                        xModifier = 0;
                    }
                    xval += xModifier;
                    yval += yModifier;
                    if (aminoClass.IsAminoAcid(item))
                    {
                        if (polarity = aminoClass.IsPolar(item))
                        {
                            canvas.DrawCircle(xval, yval, (AMINORADIUS * percentDiff), PolarAminoAcid);
                        }
                        else
                        {
                            canvas.DrawCircle(xval, yval, (AMINORADIUS * percentDiff), NonPolarAminoAcid);
                        }
                    }
                    else
                    {
                        canvas.DrawCircle(xval, yval, (AMINORADIUS * percentDiff), InvalidAminoAcid);
                    }
                    angle += 100;
                    if (angle > 360)
                    {
                        angle -= 360;
                    }
                    lastAmino = item;
                }
            }
            if (!string.IsNullOrWhiteSpace(lastAmino))
            {
                if (polarity)
                {
                    canvas.DrawText(lastAmino.Substring(0, 1).ToString().ToUpper() + lastAmino.Substring(1, 2) + incr, xval - (7 * percentDiff), yval + (4 * percentDiff), PolarLetters);
                }
                else
                {
                    canvas.DrawText(lastAmino.Substring(0, 1).ToString().ToUpper() + lastAmino.Substring(1, 2) + incr, xval - (7 * percentDiff), yval + (4 * percentDiff), NonPolarLetters);
                }
            }
        }
コード例 #20
0
        private SKBitmap OrientImage(SKBitmap bitmap, SKEncodedOrigin origin)
        {
            switch (origin)
            {
            case SKEncodedOrigin.TopRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.BottomRight:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = (float)bitmap.Width / 2;
                    float py = (float)bitmap.Height / 2;

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.BottomLeft:
            {
                var rotated = new SKBitmap(bitmap.Width, bitmap.Height);
                using (var surface = new SKCanvas(rotated))
                {
                    float px = (float)bitmap.Width / 2;

                    float py = (float)bitmap.Height / 2;

                    surface.Translate(rotated.Width, 0);
                    surface.Scale(-1, 1);

                    surface.RotateDegrees(180, px, py);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.LeftTop:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(rotated.Width, 0);

                        surface.RotateDegrees(90);

                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKEncodedOrigin.RightTop:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(rotated.Width, 0);
                    surface.RotateDegrees(90);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            case SKEncodedOrigin.RightBottom:
            {
                // TODO: Remove dual canvases, had trouble with flipping
                using (var rotated = new SKBitmap(bitmap.Height, bitmap.Width))
                {
                    using (var surface = new SKCanvas(rotated))
                    {
                        surface.Translate(0, rotated.Height);
                        surface.RotateDegrees(270);
                        surface.DrawBitmap(bitmap, 0, 0);
                    }

                    var flippedBitmap = new SKBitmap(rotated.Width, rotated.Height);
                    using (var flippedCanvas = new SKCanvas(flippedBitmap))
                    {
                        flippedCanvas.Translate(flippedBitmap.Width, 0);
                        flippedCanvas.Scale(-1, 1);
                        flippedCanvas.DrawBitmap(rotated, 0, 0);
                    }

                    return(flippedBitmap);
                }
            }

            case SKEncodedOrigin.LeftBottom:
            {
                var rotated = new SKBitmap(bitmap.Height, bitmap.Width);
                using (var surface = new SKCanvas(rotated))
                {
                    surface.Translate(0, rotated.Height);
                    surface.RotateDegrees(270);
                    surface.DrawBitmap(bitmap, 0, 0);
                }

                return(rotated);
            }

            default: return(bitmap);
            }
        }
コード例 #21
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            float x = (info.Width - monkeyBitmap.Width) / 2;
            float y = info.Height - monkeyBitmap.Height;

            // Draw monkey bitmap
            if (step >= 1)
            {
                canvas.DrawBitmap(monkeyBitmap, x, y);
            }

            // Draw matte to exclude monkey's surroundings
            if (step >= 2)
            {
                using (SKPaint paint = new SKPaint())
                {
                    paint.BlendMode = SKBlendMode.DstIn;
                    canvas.DrawBitmap(matteBitmap, x, y, paint);
                }
            }

            const float sidewalkHeight = 80;
            SKRect      rect           = new SKRect(info.Rect.Left, info.Rect.Bottom - sidewalkHeight,
                                                    info.Rect.Right, info.Rect.Bottom);

            // Draw gravel sidewalk for monkey to sit on
            if (step >= 3)
            {
                using (SKPaint paint = new SKPaint())
                {
                    paint.Shader = SKShader.CreateCompose(
                        SKShader.CreateColor(SKColors.SandyBrown),
                        SKShader.CreatePerlinNoiseTurbulence(0.1f, 0.3f, 1, 9));

                    paint.BlendMode = SKBlendMode.DstOver;
                    canvas.DrawRect(rect, paint);
                }
            }

            // Draw bitmap tiled brick wall behind monkey
            if (step >= 4)
            {
                using (SKPaint paint = new SKPaint())
                {
                    SKBitmap bitmap  = BrickWallTile;
                    float    yAdjust = (info.Height - sidewalkHeight) % bitmap.Height;

                    paint.Shader = SKShader.CreateBitmap(bitmap,
                                                         SKShaderTileMode.Repeat,
                                                         SKShaderTileMode.Repeat,
                                                         SKMatrix.MakeTranslation(0, yAdjust));
                    paint.BlendMode = SKBlendMode.DstOver;
                    canvas.DrawRect(info.Rect, paint);
                }
            }
        }
コード例 #22
0
        private void PressureDisplay_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            int h     = info.Height;
            int w     = info.Width;
            int bound = status.RecentPressMeasurements.Capacity() - 1;

            float wIncr   = w / status.RecentPressMeasurements.Capacity();
            float thisMax = 0;
            float thisMin = float.MaxValue;

            float startVal = status.RecentPressMeasurements.Get(0);

            if (startVal > thisMax)
            {
                thisMax = startVal;
            }
            if (startVal < thisMin)
            {
                thisMin = startVal;
            }

            float divDiff = MaxPress - MinPress;

            float startY = (startVal - MinPress) / (divDiff * 1.1f);

            startY = h - (startY * h);
            float startX = w;

            for (int i = 0; i < bound; i++)
            {
                float endX = startX - wIncr;

                float endVal = status.RecentPressMeasurements.Get(i + 1);
                if (endVal > thisMax)
                {
                    thisMax = endVal;
                }

                float endY = (endVal - MinPress) / (divDiff * 1.1f);
                endY = h - (endY * h);

                canvas.DrawLine(startX, startY - 5, endX, endY - 5, PressPaint);

                startX = endX;
                startY = endY;

                if (startVal < thisMin)
                {
                    thisMin = startVal;
                }
            }
            canvas.RotateDegrees(-90);
            canvas.DrawText("Pressure (kPa)", new SKPoint(-h / 2, 10), new SKPaint {
                Color = SKColors.Black
            });
            canvas.RotateDegrees(90);
            canvas.DrawText($"{((int)(MaxPress * 10)) / 10000f}", new SKPoint(10, 10), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText($"{((int)(MinPress * 10)) / 10000f}", new SKPoint(10, h - 10), new SKPaint {
                Color = SKColors.Black
            });

            canvas.DrawText("Time", new SKPoint(w / 2, h), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText("Now", new SKPoint(20, h), new SKPaint {
                Color = SKColors.Black
            });
            canvas.DrawText("Previously", new SKPoint(w - 60, h), new SKPaint {
                Color = SKColors.Black
            });

            canvas.DrawText($"PEEP: {((int)(status.Peep * 10)) / 10000f}", new SKPoint(w / 2, 15), new SKPaint {
                Color = SKColors.Black
            });

            MaxPress = Math.Max(1, (MaxPress + thisMax) / 2);
            MinPress = Math.Min((MinPress + thisMin) / 2, MaxPress - 500);
        }
コード例 #23
0
 /// <summary>
 /// The chart specific implementation of the charts drawing.
 /// </summary>
 protected abstract void DrawSpecific(SKCanvas canvas, int width, int height);
コード例 #24
0
ファイル: Chart.cs プロジェクト: punker76/Microcharts
        public void Draw(SKCanvas canvas, int width, int height)
        {
            canvas.Clear(BackgroundColor);

            this.DrawContent(canvas, width, height);
        }
コード例 #25
0
        /// <summary>
        /// Draw the describtions. So far, this is chart unspecific.
        /// </summary>
        protected void DrawValueLabels(SKCanvas canvas, int width, int height)
        {
            if (FigureAccesses == null || FigureAccesses.Count == 0)
            {
                return;
            }

            using (var describtionPaint = new SKPaint()
            {
                TextSize = 20f,
                IsAntialias = IsAntiAliased,
                Color = SKColors.Black,
                IsStroke = false
            })
            {
                //Calculating the maximum line height, that is then used for every line.
                float maxDescribtionHeight = 0f;
                foreach (FigureAccess fig in FigureAccesses)
                {
                    if (!string.IsNullOrWhiteSpace(fig.Describtion))
                    {
                        var describtionBounds = new SKRect();
                        describtionPaint.MeasureText(fig.Describtion, ref describtionBounds);
                        maxDescribtionHeight = Math.Max(maxDescribtionHeight, describtionBounds.Height);
                    }
                }

                DrawDescribtionBackGround(canvas, width, height, maxDescribtionHeight, FigureAccesses.Count);



                for (int i = 0; i < this.FigureAccesses.Count(); i++)
                {
                    FigureAccess figure = FigureAccesses.ElementAt(i);
                    if (!string.IsNullOrEmpty(figure.Describtion))
                    {
                        var    describtionBounds = new SKRect();
                        string text = figure.Describtion;
                        describtionPaint.MeasureText(text, ref describtionBounds);
                        maxDescribtionHeight = Math.Max(maxDescribtionHeight, describtionBounds.Height);


                        float xOffset       = 0;
                        float yOffset       = 0;
                        float xStep         = 0;
                        float yStep         = 0;
                        int   adjustedIndex = i;

                        switch (DescribtionPosition)
                        {
                        case DescribtionArea.Default:
                        case DescribtionArea.LeftAndRight:
                            bool halfDone = i < (this.FigureAccesses.Count() + 1) / 2;
                            adjustedIndex = halfDone ? i : i - this.FigureAccesses.Count() % 2 - this.FigureAccesses.Count() / 2;
                            xOffset       = halfDone ? width - Padding - DescribtionSpace + DescribtionPadding : +Padding + DescribtionPadding;
                            yOffset       = halfDone ? Padding + DescribtionPadding : +Padding + DescribtionPadding + ((height - 2 * Padding) - Math.Min((this.FigureAccesses.Count() / 2) * maxDescribtionHeight * DescribtionSpacing + DescribtionPadding, height - 2 * Padding));
                            xStep         = 0;
                            yStep         = maxDescribtionHeight * DescribtionSpacing;
                            break;

                        case DescribtionArea.Right:
                            xOffset = width - Padding - DescribtionSpace + DescribtionPadding;
                            yOffset = Padding + DescribtionPadding;
                            xStep   = 0;
                            yStep   = maxDescribtionHeight * DescribtionSpacing;
                            break;

                        case DescribtionArea.Left:
                            xOffset = +Padding + DescribtionPadding;
                            yOffset = +Padding + DescribtionPadding;
                            xStep   = 0;
                            yStep   = maxDescribtionHeight * DescribtionSpacing;
                            break;

                        case DescribtionArea.Top:
                            break;

                        case DescribtionArea.Bottom:
                            break;

                        default:
                            break;
                        }

                        SKRect colorRect = SKRect.Create(
                            x: xOffset + xStep * adjustedIndex,
                            y: yOffset + yStep * adjustedIndex,
                            width: maxDescribtionHeight,
                            height: maxDescribtionHeight
                            );

                        using (var paint = new SKPaint()
                        {
                            IsAntialias = IsAntiAliased,
                            Color = figure.Color,
                            Style = SKPaintStyle.Fill
                        }) canvas.DrawRect(colorRect, paint);

                        canvas.DrawText(text,
                                        x: colorRect.Right + 3f,
                                        y: colorRect.Bottom,
                                        paint: describtionPaint);

                        float  valToShow = AnimateVisibleValues ? figure.AnimatedValue : figure.Value;
                        string valText   = Math.Round(valToShow, FractionalDigits).ToString("n" + FractionalDigits);

                        canvas.DrawText(
                            text: valText,
                            x: colorRect.Right + describtionBounds.Width + 9f,
                            y: colorRect.Bottom,
                            paint: describtionPaint);
                    }
                }
            }
        }
コード例 #26
0
        public void OnDrawFrame(IGL10 gl)
        {
            GLES10.GlClear(GLES10.GlColorBufferBit | GLES10.GlDepthBufferBit | GLES10.GlStencilBufferBit);

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

            // manage the drawing surface
            if (renderTarget == null || lastSize != newSize || !renderTarget.IsValid)
            {
                // create or update the dimensions
                lastSize = newSize;

                // read the info from the buffer
                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;
                }
                glInfo = new GRGlFramebufferInfo((uint)buffer[0], colorType.ToGlSizedFormat());

                // destroy the old surface
                surface?.Dispose();
                surface = null;
                canvas  = null;

                // re-create the render target
                renderTarget?.Dispose();
                renderTarget = new GRBackendRenderTarget(newSize.Width, newSize.Height, samples, buffer[1], glInfo);
            }

            // create the surface
            if (surface == null)
            {
                surface = SKSurface.Create(context, renderTarget, surfaceOrigin, colorType);
                canvas  = surface.Canvas;
            }

            using (new SKAutoCanvasRestore(canvas, true))
            {
                // start drawing
                var e = new SKPaintGLSurfaceEventArgs(surface, renderTarget, surfaceOrigin, colorType, glInfo);
                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
            canvas.Flush();
            context.Flush();
        }
コード例 #27
0
        /// <summary>
        /// Draw the describtion background. So far, this is chart unspecific.
        /// </summary>
        /// <param name="maxDescribtionHeight">Maximal height of the describtions. </param>
        /// <param name="figureAmount">The figure count</param>
        private void DrawDescribtionBackGround(SKCanvas canvas, float width, float height, float maxDescribtionHeight, int figureAmount)
        {
            using (var describtionBackGroundPaint = new SKPaint()
            {
                Color = SKColors.DarkGray,
                Style = SKPaintStyle.Stroke,
                StrokeWidth = 4f,
                PathEffect = SKPathEffect.CreateDash(new float[] { 10f, 10f }, 0)
            })
                switch (DescribtionPosition)
                {
                case DescribtionArea.Default:
                    break;

                case DescribtionArea.LeftAndRight:

                    int rightVals = (figureAmount + 1) / 2;
                    int leftVals  = figureAmount / 2;

                    float rightHeight = Math.Min(rightVals * maxDescribtionHeight * DescribtionSpacing + DescribtionPadding, height - 2 * Padding);
                    float leftHeight  = Math.Min(leftVals * maxDescribtionHeight * DescribtionSpacing + DescribtionPadding, height - 2 * Padding);

                    float leftYOffset = (height - 2 * Padding) - leftHeight;

                    canvas.DrawRoundRect(
                        x: width - Padding - DescribtionSpace,
                        y: Padding,
                        w: DescribtionSpace,
                        h: rightHeight,
                        rx: 3, ry: 3,
                        paint: describtionBackGroundPaint);

                    canvas.DrawRoundRect(
                        x: Padding,
                        y: Padding + leftYOffset,
                        w: DescribtionSpace,
                        h: leftHeight,
                        rx: 3, ry: 3,
                        paint: describtionBackGroundPaint);
                    break;

                case DescribtionArea.Right:
                    canvas.DrawRoundRect(
                        x: width - Padding - DescribtionSpace,
                        y: Padding,
                        w: DescribtionSpace,
                        h: Math.Min(figureAmount * maxDescribtionHeight * DescribtionSpacing + DescribtionPadding, height - 2 * Padding),
                        rx: 3, ry: 3,
                        paint: describtionBackGroundPaint);
                    break;

                case DescribtionArea.Left:
                    canvas.DrawRoundRect(
                        x: Padding,
                        y: Padding,
                        w: DescribtionSpace,
                        h: Math.Min(figureAmount * maxDescribtionHeight * DescribtionSpacing + DescribtionPadding, height - 2 * Padding),
                        rx: 3, ry: 3,
                        paint: describtionBackGroundPaint);
                    break;

                case DescribtionArea.Top:
                    break;

                case DescribtionArea.Bottom:
                    break;

                default:
                    break;
                }
        }
コード例 #28
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear(SKColors.Transparent);

            using (var bitmap = masterBitmap.Copy())
            {
                float scale = Math.Min((float)info.Width / bitmap.Width,
                                       (float)info.Height / bitmap.Height);
                float  x        = (info.Width - scale * bitmap.Width) / 2;
                float  y        = (info.Height - scale * bitmap.Height) / 2;
                SKRect destRect = new SKRect(x, y, x + scale * bitmap.Width,
                                             y + scale * bitmap.Height);

                if (predictions != null)
                {
                    // draw directly on the bitmap
                    using (var annotationCanvas = new SKCanvas(bitmap))
                        using (var textPaint = new SKPaint())
                            using (var boxPaint = new SKPaint())
                            {
                                boxPaint.StrokeWidth = 3 / scale;
                                textPaint.TextSize   = 25 / scale;
                                boxPaint.Style       = SKPaintStyle.Stroke;


                                foreach (var result in predictions)
                                {
                                    // Draw the bounding box
                                    var rect = result.BoundingBox;
                                    var zone = SKRectI.Create(
                                        (int)(rect.Left * bitmap.Width),
                                        (int)(rect.Top * bitmap.Height),
                                        (int)(rect.Width * bitmap.Width),
                                        (int)(rect.Height * bitmap.Height));

                                    boxPaint.Color = SKColors.Red;
                                    annotationCanvas.DrawRect(zone, boxPaint);

                                    // Draw the textbox
                                    textPaint.Color        = SKColors.Red;
                                    textPaint.FakeBoldText = true;
                                    //var textBox = SKRectI.Create(zone.Left, zone.Top - textPaint.TextSize, );

                                    var message = result.TagName + ":" + Math.Round(result.Probability, 2);
                                    annotationCanvas.DrawText(message, zone.Left + 10, zone.Top - textPaint.TextSize, textPaint);
                                }
                            }
                }

                // Resizing
                //var pictureFrame = canvasView.Bounds.ToSKRect();
                //var imageSize = new SKSize(bitmap.Width, bitmap.Height);
                //var dest = pictureFrame.AspectFill(imageSize);

                // draw the image
                //var paint = new SKPaint
                //{
                //	FilterQuality = SKFilterQuality.High // high quality scaling
                //};

                // draw the modified bitmap to the screen
                canvas.DrawBitmap(bitmap, destRect);
            }
        }
コード例 #29
0
ファイル: SKDrawable.cs プロジェクト: wieslawsoltes/Svg.Skia
 protected virtual void OnDraw(SKCanvas canvas)
 {
 }
コード例 #30
0
		/// <summary>
		///     Override this method to implement the drawing routine for the control
		/// </summary>
		/// <param name="canvas">The Skia canvas</param>
		/// <param name="width">Canvas width</param>
		/// <param name="height">Canvas height</param>
		protected abstract void Draw(SKCanvas canvas, int width, int height);
コード例 #31
0
        internal void Draw(DrawingContextImpl context,
                           SKCanvas canvas,
                           SKPoint origin,
                           DrawingContextImpl.PaintWrapper foreground,
                           bool canUseLcdRendering)
        {
            /* TODO: This originated from Native code, it might be useful for debugging character positions as
             * we improve the FormattedText support. Will need to port this to C# obviously. Rmove when
             * not needed anymore.
             *
             *  SkPaint dpaint;
             *  ctx->Canvas->save();
             *  ctx->Canvas->translate(origin.fX, origin.fY);
             *  for (int c = 0; c < Lines.size(); c++)
             *  {
             *      dpaint.setARGB(255, 0, 0, 0);
             *      SkRect rc;
             *      rc.fLeft = 0;
             *      rc.fTop = Lines[c].Top;
             *      rc.fRight = Lines[c].Width;
             *      rc.fBottom = rc.fTop + LineOffset;
             *      ctx->Canvas->drawRect(rc, dpaint);
             *  }
             *  for (int c = 0; c < Length; c++)
             *  {
             *      dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10);
             *      dpaint.setStyle(SkPaint::kFill_Style);
             *      ctx->Canvas->drawRect(Rects[c], dpaint);
             *  }
             *  ctx->Canvas->restore();
             */
            using (var paint = _paint.Clone())
            {
                IDisposable currd          = null;
                var         currentWrapper = foreground;
                SKPaint     currentPaint   = null;
                try
                {
                    ApplyWrapperTo(ref currentPaint, foreground, ref currd, paint, canUseLcdRendering);
                    bool hasCusomFGBrushes = _foregroundBrushes.Any();

                    for (int c = 0; c < _skiaLines.Count; c++)
                    {
                        AvaloniaFormattedTextLine line = _skiaLines[c];

                        float x = TransformX(origin.X, 0, paint.TextAlign);

                        if (!hasCusomFGBrushes)
                        {
                            var subString = Text.Substring(line.Start, line.Length);
                            canvas.DrawText(subString, x, origin.Y + line.Top + _lineOffset, paint);
                        }
                        else
                        {
                            float  currX = x;
                            string subStr;
                            float  measure;
                            int    len;
                            float  factor;
                            switch (paint.TextAlign)
                            {
                            case SKTextAlign.Left:
                                factor = 0;
                                break;

                            case SKTextAlign.Center:
                                factor = 0.5f;
                                break;

                            case SKTextAlign.Right:
                                factor = 1;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }

                            var textLine = Text.Substring(line.Start, line.Length);
                            currX -= textLine.Length == 0 ? 0 : paint.MeasureText(textLine) * factor;

                            for (int i = line.Start; i < line.Start + line.Length;)
                            {
                                var fb = GetNextForegroundBrush(ref line, i, out len);

                                if (fb != null)
                                {
                                    //TODO: figure out how to get the brush size
                                    currentWrapper = context.CreatePaint(fb, new Size());
                                }
                                else
                                {
                                    if (!currentWrapper.Equals(foreground))
                                    {
                                        currentWrapper.Dispose();
                                    }
                                    currentWrapper = foreground;
                                }

                                subStr  = Text.Substring(i, len);
                                measure = paint.MeasureText(subStr);
                                currX  += measure * factor;

                                ApplyWrapperTo(ref currentPaint, currentWrapper, ref currd, paint, canUseLcdRendering);

                                canvas.DrawText(subStr, currX, origin.Y + line.Top + _lineOffset, paint);

                                i     += len;
                                currX += measure * (1 - factor);
                            }
                        }
                    }
                }
                finally
                {
                    if (!currentWrapper.Equals(foreground))
                    {
                        currentWrapper.Dispose();
                    }
                    currd?.Dispose();
                }
            }
        }