Esempio n. 1
0
        private void RenderImage(Color c, double width, double height)
        {
            double ratio = height / 300;
            var    isSq  = width == height;

            Vector2 vector2 = new Vector2((float)(ZoomF * ratio));

            var effect = new Transform2DEffect
            {
                Source            = UserBitmap,
                InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                TransformMatrix   = Matrix3x2.CreateScale(vector2)
            };

            if (isSq && IsManualAdjustSquareImage)
            {
                effect = new Transform2DEffect
                {
                    Source            = UserBitmap,
                    InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                    TransformMatrix   = Matrix3x2.CreateScale(new Vector2((float)(SZoomF * ratio)))
                };
            }

            //Render target: Main render
            if (isSq)
            {
                PlexibleX    = X - 160;
                RenderTarget = new CanvasRenderTarget(_device, (float)(300 * ratio), (float)(300 * ratio), 96);
                if (IsManualAdjustSquareImage)
                {
                    //Square
                    SRenderTarget = new CanvasRenderTarget(_device, (float)(300 * ratio), (float)(300 * ratio), 96);
                }
            }
            else if (width > height)
            {
                RenderTarget = new CanvasRenderTarget(_device, (float)(620 * ratio), (float)(300 * ratio), 96);
                PlexibleX    = X;
            }

            if (isSq && IsManualAdjustSquareImage)
            {
                using (var ds = SRenderTarget.CreateDrawingSession())
                {
                    //Clear the color
                    ds.Clear(c);

                    //Draw the user image to target
                    ds.DrawImage(effect, (float)(SX * ratio), (float)(SY * ratio),
                                 new Rect(SRecX, SRecY, SRecW * ratio, SRecH * ratio), 1.0f,
                                 CanvasImageInterpolation.HighQualityCubic);
                }
            }
            else
            {
                using (var ds = RenderTarget.CreateDrawingSession())
                {
                    //Clear the color
                    ds.Clear(c);

                    //Draw the user image to target
                    ds.DrawImage(effect, (float)(PlexibleX * ratio), (float)(Y * ratio),
                                 new Rect(RecX, RecY, RecW * ratio, RecH * ratio), 1.0f, CanvasImageInterpolation.HighQualityCubic);
                }
            }
        }
Esempio n. 2
0
        private static Image CutImage(Texture2D m_Texture2D, Sprite m_Sprite, Rectf textureRect, Vector2 textureRectOffset, SpriteSettings settingsRaw)
        {
            var originalImage = m_Texture2D.ConvertToImage(false);

            if (originalImage != null)
            {
                using (originalImage)
                {
                    var rectX      = (int)Math.Floor(textureRect.x);
                    var rectY      = (int)Math.Floor(textureRect.y);
                    var rectRight  = (int)Math.Ceiling(textureRect.x + textureRect.width);
                    var rectBottom = (int)Math.Ceiling(textureRect.y + textureRect.height);
                    rectRight  = Math.Min(rectRight, m_Texture2D.m_Width);
                    rectBottom = Math.Min(rectBottom, m_Texture2D.m_Height);
                    var rect        = new Rectangle(rectX, rectY, rectRight - rectX, rectBottom - rectY);
                    var spriteImage = originalImage.Clone(x => x.Crop(rect));
                    if (settingsRaw.packed == 1)
                    {
                        //RotateAndFlip
                        switch (settingsRaw.packingRotation)
                        {
                        case SpritePackingRotation.kSPRFlipHorizontal:
                            spriteImage.Mutate(x => x.Flip(FlipMode.Horizontal));
                            break;

                        case SpritePackingRotation.kSPRFlipVertical:
                            spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                            break;

                        case SpritePackingRotation.kSPRRotate180:
                            spriteImage.Mutate(x => x.Rotate(180));
                            break;

                        case SpritePackingRotation.kSPRRotate90:
                            spriteImage.Mutate(x => x.Rotate(270));
                            break;
                        }
                    }

                    //Tight
                    if (settingsRaw.packingMode == SpritePackingMode.kSPMTight)
                    {
                        try
                        {
                            var             triangles = GetTriangles(m_Sprite.m_RD);
                            var             polygons  = triangles.Select(x => new Polygon(new LinearLineSegment(x.Select(y => new PointF(y.X, y.Y)).ToArray()))).ToArray();
                            IPathCollection path      = new PathCollection(polygons);
                            var             matrix    = Matrix3x2.CreateScale(m_Sprite.m_PixelsToUnits);
                            var             version   = m_Sprite.version;
                            if (version[0] < 5 ||
                                (version[0] == 5 && version[1] < 4) ||
                                (version[0] == 5 && version[1] == 4 && version[2] <= 1))   //5.4.1p3 down
                            {
                                matrix *= Matrix3x2.CreateTranslation(m_Sprite.m_Rect.width * 0.5f - textureRectOffset.X, m_Sprite.m_Rect.height * 0.5f - textureRectOffset.Y);
                            }
                            else
                            {
                                matrix *= Matrix3x2.CreateTranslation(m_Sprite.m_Rect.width * m_Sprite.m_Pivot.X - textureRectOffset.X, m_Sprite.m_Rect.height * m_Sprite.m_Pivot.Y - textureRectOffset.Y);
                            }
                            path = path.Transform(matrix);
                            var options = new DrawingOptions
                            {
                                GraphicsOptions = new GraphicsOptions()
                                {
                                    AlphaCompositionMode = PixelAlphaCompositionMode.DestOut
                                }
                            };
                            var rectP = new RectangularPolygon(0, 0, rect.Width, rect.Height);
                            spriteImage.Mutate(x => x.Fill(options, SixLabors.ImageSharp.Color.Red, rectP.Clip(path)));
                            spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                            return(spriteImage);
                        }
                        catch
                        {
                            // ignored
                        }
                    }

                    //Rectangle
                    spriteImage.Mutate(x => x.Flip(FlipMode.Vertical));
                    return(spriteImage);
                }
            }

            return(null);
        }
 /// <summary>
 /// Prepends a scale matrix from the given uniform scale.
 /// </summary>
 /// <param name="scale">The uniform scale.</param>
 /// <returns>The <see cref="AffineTransformBuilder"/>.</returns>
 public AffineTransformBuilder PrependScale(float scale)
 => this.PrependMatrix(Matrix3x2.CreateScale(scale));
Esempio n. 4
0
 public void Scale(float sx, float sy)
 {
     _state.Transform = Matrix3x2.Multiply(Matrix3x2.CreateScale(sx, sy), _state.Transform);
 }
Esempio n. 5
0
 public void ScaleTransform(float sx, float sy)
 {
     Transform = Matrix3x2.CreateScale(sx, sy) * Transform;
 }
Esempio n. 6
0
        protected override void drawChart(CanvasDrawingSession canvas)
        {
            if (chartData != null)
            {
                float fullWidth = (chartWidth / (pickerDelegate.pickerEnd - pickerDelegate.pickerStart));
                float offset    = fullWidth * (pickerDelegate.pickerStart) - HORIZONTAL_PADDING;

                int start = startXIndex - 1;
                if (start < 0)
                {
                    start = 0;
                }
                int end = endXIndex + 1;
                if (end > chartData.lines[0].y.Length - 1)
                {
                    end = chartData.lines[0].y.Length - 1;
                }

                //canvas.save();
                //canvas.clipRect(chartStart, 0, chartEnd, getMeasuredHeight() - chartBottom);
                var transform = canvas.Transform;
                var clip      = canvas.CreateLayer(1, createRect(chartStart, 0, chartEnd, getMeasuredHeight() - chartBottom));

                float transitionAlpha = 1f;
                //canvas.save();
                if (transitionMode == TRANSITION_MODE_PARENT)
                {
                    postTransition  = true;
                    selectionA      = 0f;
                    transitionAlpha = 1f - transitionParams.progress;

                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(1 + 2 * transitionParams.progress, 1f),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }
                else if (transitionMode == TRANSITION_MODE_CHILD)
                {
                    transitionAlpha = transitionParams.progress;

                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(transitionParams.progress, 1f),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }


                for (int k = 0; k < lines.Count; k++)
                {
                    BarViewData line = lines[k];
                    if (!line.enabled && line.alpha == 0)
                    {
                        continue;
                    }

                    float p;
                    if (chartData.xPercentage.Length < 2)
                    {
                        p = 1f;
                    }
                    else
                    {
                        p = chartData.xPercentage[1] * fullWidth;
                    }
                    int[] y = line.line.y;
                    int   j = 0;

                    float selectedX = 0f;
                    float selectedY = 0f;
                    bool  selected  = false;
                    float a         = line.alpha;
                    for (int i = start; i <= end; i++)
                    {
                        float xPoint      = p / 2 + chartData.xPercentage[i] * fullWidth - offset;
                        float yPercentage = y[i] / currentMaxHeight * a;

                        float yPoint = getMeasuredHeight() - chartBottom - (yPercentage) * (getMeasuredHeight() - chartBottom - SIGNATURE_TEXT_HEIGHT);

                        if (i == selectedIndex && legendShowing)
                        {
                            selected  = true;
                            selectedX = xPoint;
                            selectedY = yPoint;
                            continue;
                        }

                        line.linesPath[j++] = xPoint;
                        line.linesPath[j++] = yPoint;

                        line.linesPath[j++] = xPoint;
                        line.linesPath[j++] = getMeasuredHeight() - chartBottom;
                    }

                    Paint paint = selected || postTransition ? line.unselectedPaint : line.paint;
                    paint.StrokeWidth = p;
                    //paint.setStrokeWidth(p);


                    if (selected)
                    {
                        line.unselectedPaint.Color = Extensions.blendARGB(
                            line.line.color, line.blendColor, 1f - selectionA);
                    }

                    if (postTransition)
                    {
                        line.unselectedPaint.Color = Extensions.blendARGB(
                            line.line.color, line.blendColor, 0);
                    }

                    paint.A = (byte)(transitionAlpha * 255);
                    //canvas.drawLines(line.linesPath, 0, j, paint);
                    canvas.DrawLines(line.linesPath, 0, j, paint);

                    if (selected)
                    {
                        //line.paint.setStrokeWidth(p);
                        line.paint.StrokeWidth = p;
                        line.paint.A           = (byte)(transitionAlpha * 255);
                        //canvas.drawLine(selectedX, selectedY,
                        //        selectedX, getMeasuredHeight() - chartBottom,
                        //        line.paint
                        //);
                        canvas.DrawLine(selectedX, selectedY, selectedX, getMeasuredHeight() - chartBottom, line.paint);
                        line.paint.A = 255;
                    }
                }

                //canvas.restore();
                //canvas.restore();
                clip.Dispose();
                canvas.Transform = transform;
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Creates a path translated by the supplied postion
 /// </summary>
 /// <param name="path">The path to translate.</param>
 /// <param name="scaleX">The amount to scale along the X axis.</param>
 /// <param name="scaleY">The amount to scale along the Y axis.</param>
 /// <returns>A <see cref="IPath"/> with a translate transform applied.</returns>
 public static IPath Scale(this IPath path, float scaleX, float scaleY)
 {
     return(path.Transform(Matrix3x2.CreateScale(scaleX, scaleY, RectangleF.Center(path.Bounds))));
 }
Esempio n. 8
0
            Matrix3x2 GetDirectionTransform(CanvasTextDirection direction)
            {
                var       arrowBounds        = arrow.ComputeStrokeBounds(4);
                var       arrowCenter        = new Size(arrowBounds.Width, arrowBounds.Height).ToVector2() / 2;
                Matrix3x2 directionTransform = Matrix3x2.Identity;

                switch (direction)
                {
                case CanvasTextDirection.LeftToRightThenTopToBottom:
                    directionTransform = Matrix3x2.Identity;
                    break;

                case CanvasTextDirection.RightToLeftThenTopToBottom:
                    directionTransform = Matrix3x2.CreateScale(-1, 1);
                    break;

                case CanvasTextDirection.LeftToRightThenBottomToTop:
                    directionTransform = Matrix3x2.CreateScale(1, -1);
                    break;

                case CanvasTextDirection.RightToLeftThenBottomToTop:
                    directionTransform = Matrix3x2.CreateScale(-1, -1);
                    break;

                case CanvasTextDirection.TopToBottomThenLeftToRight:
                    directionTransform = Matrix3x2.CreateRotation((float)Math.PI / 2) * Matrix3x2.CreateScale(-1, 1);
                    break;

                case CanvasTextDirection.BottomToTopThenLeftToRight:
                    directionTransform = Matrix3x2.CreateRotation((float)-Math.PI / 2);
                    break;

                case CanvasTextDirection.TopToBottomThenRightToLeft:
                    directionTransform = Matrix3x2.CreateRotation((float)Math.PI / 2);
                    break;

                case CanvasTextDirection.BottomToTopThenRightToLeft:
                    directionTransform = Matrix3x2.CreateRotation((float)-Math.PI / 2) * Matrix3x2.CreateScale(-1, 1);
                    break;
                }

                directionTransform = Matrix3x2.CreateTranslation(-arrowCenter) * directionTransform * Matrix3x2.CreateTranslation(arrowCenter);
                return(directionTransform);
            }
        public void DrawMirrored(CanvasAnimatedDrawEventArgs args, Vector2 position)
        {
            Matrix3x2 push = args.DrawingSession.Transform;

            args.DrawingSession.Transform = Matrix3x2.CreateRotation((float)(_rotation * Math.PI / 180), position) * Matrix3x2.CreateScale(-1, 1, position);
            args.DrawingSession.DrawTextLayout(TextLayout, position, _color);
            args.DrawingSession.Transform = push;
        }
Esempio n. 10
0
        private ICanvasImage CreateLighting()
        {
            var heightMap = new LuminanceToAlphaEffect
            {
                Source = bitmapTiger
            };

            var distantDiffuseEffect = new DistantDiffuseEffect
            {
                Source         = heightMap,
                HeightMapScale = 2
            };

            var distantSpecularEffect = new DistantSpecularEffect
            {
                Source           = heightMap,
                SpecularExponent = 16
            };

            var pointDiffuseEffect = new PointDiffuseEffect
            {
                Source         = heightMap,
                HeightMapScale = 2
            };

            var pointSpecularEffect = new PointSpecularEffect
            {
                Source           = heightMap,
                SpecularExponent = 16
            };

            var spotDiffuseEffect = new SpotDiffuseEffect
            {
                Source            = heightMap,
                HeightMapScale    = 2,
                LimitingConeAngle = 0.25f,
                LightTarget       = new Vector3(bitmapTiger.Size.ToVector2(), 0) / 2
            };

            var spotSpecularEffect = new SpotSpecularEffect
            {
                Source            = heightMap,
                SpecularExponent  = 16,
                LimitingConeAngle = 0.25f,
                LightTarget       = new Vector3(bitmapTiger.Size.ToVector2(), 0) / 2
            };

            // Lay out all the different light types in a grid.
            var xgap = (float)bitmapTiger.Size.Width * 1.1f;
            var ygap = (float)bitmapTiger.Size.Height * 1.1f;

            var compositeEffect = new CompositeEffect
            {
                Sources =
                {
                    AddTextOverlay(distantDiffuseEffect,                            -xgap, -ygap),
                    AddTextOverlay(distantSpecularEffect,                           -xgap,     0),
                    AddTextOverlay(pointDiffuseEffect,                                 -0, -ygap),
                    AddTextOverlay(pointSpecularEffect,                                -0,     0),
                    AddTextOverlay(spotDiffuseEffect,               xgap,                  -ygap),
                    AddTextOverlay(spotSpecularEffect,              xgap,                      0),

                    CombineDiffuseAndSpecular(distantDiffuseEffect, distantSpecularEffect,  -xgap,ygap),
                    CombineDiffuseAndSpecular(pointDiffuseEffect,   pointSpecularEffect,        0,ygap),
                    CombineDiffuseAndSpecular(spotDiffuseEffect,    spotSpecularEffect,    xgap,  ygap),
                }
            };

            ICanvasImage finalEffect = compositeEffect;

            // Check the screen size, and scale down our output if the screen is too small to fit the whole thing as-is.
            var xScaleFactor = (float)canvas.ActualWidth / 750;
            var yScaleFactor = (float)canvas.ActualHeight / 500;

            var scaleFactor = Math.Min(xScaleFactor, yScaleFactor);

            if (scaleFactor < 1)
            {
                finalEffect = new Transform2DEffect
                {
                    Source          = compositeEffect,
                    TransformMatrix = Matrix3x2.CreateScale(scaleFactor, bitmapTiger.Size.ToVector2() / 2)
                };
            }

            // Animation changes the light directions.
            animationFunction = elapsedTime =>
            {
                distantDiffuseEffect.Azimuth      =
                    distantSpecularEffect.Azimuth = elapsedTime % ((float)Math.PI * 2);

                distantDiffuseEffect.Elevation      =
                    distantSpecularEffect.Elevation = (float)Math.PI / 4 + (float)Math.Sin(elapsedTime / 2) * (float)Math.PI / 8;

                pointDiffuseEffect.LightPosition             =
                    pointSpecularEffect.LightPosition        =
                        spotDiffuseEffect.LightPosition      =
                            spotSpecularEffect.LightPosition = new Vector3((float)Math.Cos(elapsedTime), (float)Math.Sin(elapsedTime), 1) * 100;
            };

            return(finalEffect);
        }
Esempio n. 11
0
        /// <summary>
        /// Transformiert die Grundform eines Zeitzeigers so, dass die gewünschte Uhrzeit dargestellt wird
        /// </summary>
        /// <param name="time60">Position des Zeigers auf einer 60-er Teilung (Kreis in 60 Segmente aufgeteilt)</param>
        /// <param name="TimePointerShape">Liste aus Vektoren, welche den Unmriss des Zeigers beschreiben</param>
        /// <param name="center">Mittelpunkt des Ziffernblattes</param>
        /// <returns></returns>
        public Vector2[] SetTimePointer60(int time60, IEnumerable <Vector2> TimePointerShape)
        {
            mko.TraceHlp.ThrowArgExIfNot(0 <= time60 && time60 <= 60, "Zeigerposition ungültig");

            // Position des Sekundenzeigers berechnen
            // 1 sec <=> 6°

            // Sekunden in Winkel umrechnen

            var Deg = 90.0f - time60 * 6.0f;

            if (Deg < 0.0)
            {
                Deg = 360.0f + Deg;
            }

            // Winkel in Bogen
            var Rad = Deg * (float)Math.PI / 180.0f;


            // Koordinatentransformation als Produkt aus einer Dreh- und einer Verscheibematrix
            // Eine Spiegelung an der x- Achse wurde eingebaut, da die y- Achsen der  Koordinatensysteme im
            // Computer nach unten zeigen, und damit entgegen der Mathematik, in der sie nach oben zeigen.
            var mat = Matrix3x2.Multiply(Matrix3x2.Multiply(Matrix3x2.CreateRotation(Rad), Matrix3x2.CreateScale(1.0f, -1.0f)), Matrix3x2.CreateTranslation(CenterPoint));

            List <Vector2> transformed = new List <Vector2>(TimePointerShape.Count());

            foreach (var vec in TimePointerShape)
            {
                transformed.Add(Vector2.Transform(vec, mat));
            }

            return(transformed.ToArray());
        }
Esempio n. 12
0
        protected void CanvasAnimatedControl_Draw(Microsoft.Graphics.Canvas.UI.Xaml.ICanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedDrawEventArgs args)
        {
            // First, ensure we have exclusive access to the list of sprites. we don't want this changing while we are trying
            // to draw it. If another thread has access to it, we will skip drawing this frame.

            if (Monitor.TryEnter(Sprite.Sprites))
            {
                try
                {
                    // Establish the scale. Normally we draw at 1.0 scale. However, if the drawing surface is SMALLER than our coordinate space, we
                    // need to scale down. Likewise, if we are in fullscreen mode, we'll need to scale up.
                    if (sender.Size.Width < Dimensions.Width || sender.Size.Height < Dimensions.Height || fullscreen)
                    {
                        scale = (float)Math.Min(sender.Size.Width / Dimensions.Width, sender.Size.Height / Dimensions.Height);
                    }
                    else
                    {
                        scale = 1.0f;
                    }

                    // Draw the 'scale' transform into the scene
                    args.DrawingSession.Transform = Matrix3x2.CreateScale(scale, new Vector2((float)(sender.Size.Width / 2), (float)(sender.Size.Height / 2)));

                    // Upper-left corner of the destination drawing space
                    var origin = new Point()
                    {
                        X = (sender.Size.Width - Dimensions.Width) / 2, Y = (sender.Size.Height - Dimensions.Height) / 2
                    };

                    // Rectangle describing the destination drawing space
                    var destrect = new Rect(origin, Dimensions);

                    // Creating a layer around the destination drawing space is how we clip drawing to only the
                    // expected drawing space
                    using (args.DrawingSession.CreateLayer(1.0f, destrect))
                    {
                        // Draw the background
                        if (background != null && bitmaps.ContainsKey(background))
                        {
                            args.DrawingSession.DrawImage(bitmaps[background], destrect);
                        }

                        // The sprites are all positioned relative to the 'center', so we need to know where that is
                        // on the screen right now
                        var center = new Point(sender.Size.Width / 2, sender.Size.Height / 2);

                        // Draw each sprite
                        foreach (var sprite in Sprite.Sprites.OrderBy(x => x.Layer))
                        {
                            // Only draw the sprite if we have a costume loaded for it
                            if (sprite.Costume != null && sprite.Visible && bitmaps.ContainsKey(sprite.Costume))
                            {
                                // Fetch the correct drawing resource for this sprite
                                var bitmap = bitmaps[sprite.Costume];

                                // Figure out how big of space the sprite will occupy in the scene. This is where we
                                // apply sprite scaling. Also, this value is used for collisions.
                                sprite.CostumeSize = new Size(bitmap.Size.Width * sprite.Scale, bitmap.Size.Height * sprite.Scale);

                                // The 'drawme' is the canvas image we will ultimately draw. Along the way we will optionally
                                // apply effects to it.
                                ICanvasImage drawme = bitmap;

                                // Opacity effect if we are not fully opaque
                                if (sprite.Opacity < 1.0)
                                {
                                    drawme = new OpacityEffect()
                                    {
                                        Source  = drawme,
                                        Opacity = (float)sprite.Opacity
                                    };
                                }

                                // Rotation effect if we are rotated.
                                if (sprite.RotationAngle != 0.0)
                                {
                                    drawme = new Transform2DEffect()
                                    {
                                        Source          = drawme,
                                        TransformMatrix = Matrix3x2.CreateRotation((float)sprite.RotationAngle, new Vector2((float)bitmap.Size.Width / 2, (float)bitmap.Size.Height / 2))
                                    };
                                }

                                // Flip horizontal, if so indicated
                                if (sprite.FlipHorizontal)
                                {
                                    drawme = new Transform2DEffect()
                                    {
                                        Source          = drawme,
                                        TransformMatrix = Matrix3x2.CreateScale(-1.0f, 1.0f, new Vector2((float)bitmap.Size.Width / 2, (float)bitmap.Size.Height / 2))
                                    };
                                }

                                // Where in the scene to draw the sprite
                                var draw_at = new Point(center.X + sprite.Position.X - sprite.CostumeSize.Width / 2, center.Y - sprite.Position.Y - sprite.CostumeSize.Height / 2);

                                // Draw the sprite!
                                args.DrawingSession.DrawImage(drawme, new Rect(draw_at, sprite.CostumeSize), new Rect(new Point(0, 0), bitmap.Size));

                                // Render the 'saying'
                                if (sprite.Saying?.Length > 0)
                                {
                                    var drawingSession = args.DrawingSession;
                                    var format         = new CanvasTextFormat {
                                        FontSize = 30.0f, WordWrapping = CanvasWordWrapping.NoWrap
                                    };
                                    var textLayout = new CanvasTextLayout(drawingSession, sprite.Saying, format, 0.0f, 0.0f);

                                    float xcenter = (float)(center.X + sprite.Position.X);
                                    float ytop    = (float)(center.Y - sprite.Position.Y + bitmap.Size.Height / 2 + 10.0);

                                    var theRectYouAreLookingFor = new Rect(xcenter - textLayout.LayoutBounds.Width / 2 - 5, ytop, textLayout.LayoutBounds.Width + 10, textLayout.LayoutBounds.Height);
                                    drawingSession.FillRectangle(theRectYouAreLookingFor, Colors.White);
                                    drawingSession.DrawTextLayout(textLayout, xcenter - (float)textLayout.LayoutBounds.Width / 2, ytop, Colors.Black);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // This is not a great thing to do with exceptions...
                }
                finally
                {
                    Monitor.Exit(Sprite.Sprites);
                }
            }
        }
Esempio n. 13
0
        public void DisplayPreview()
        {
            if (File == null)
            {
                return;
            }

            //Get current color
            Color c = new Color
            {
                A = (byte)BackgroundVm.ColorBackgroundVm.A,
                R = (byte)BackgroundVm.ColorBackgroundVm.R,
                G = (byte)BackgroundVm.ColorBackgroundVm.G,
                B = (byte)BackgroundVm.ColorBackgroundVm.B
            };

            if (IsCaculation)
            {
                //Send message to output
                Debug.WriteLine("Re caculate param");

                if (UserBitmap.SizeInPixels.Width <= UserBitmap.SizeInPixels.Height)
                {
                    ZoomF = (float)300 / UserBitmap.SizeInPixels.Height;
                }
                else
                {
                    ZoomF = (float)620 / UserBitmap.SizeInPixels.Width;
                }

                X = 310 - ((UserBitmap.SizeInPixels.Width * ZoomF) / 2);
                Y = 150 - ((UserBitmap.SizeInPixels.Height * ZoomF) / 2);

                IsCaculation = false;
            }

            RecW = UserBitmap.SizeInPixels.Width * ZoomF;
            RecH = UserBitmap.SizeInPixels.Height * ZoomF;

            var effect = new Transform2DEffect
            {
                Source            = UserBitmap,
                InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                TransformMatrix   = Matrix3x2.CreateScale(new Vector2(ZoomF))
            };

            //Render target: Main render
            RenderTarget = new CanvasRenderTarget(_device, 620, 300, 96);
            using (var ds = RenderTarget.CreateDrawingSession())
            {
                //Clear the color
                ds.Clear(c);

                //Draw transperent bitmap
                ds.DrawImage(_transperentBitmap, 0, 0, new Rect(0, 0, 620, 300), 1.0f);

                //Fill the rectangle with color
                ds.FillRectangle(0, 0, 620, 300, c);

                //CreatePathLoop(ds);

                //ds.DrawGeometry(geometry, Colors.Red, 0);

                //Draw the user image to target
                ds.DrawImage(effect, X, Y, new Rect(RecX, RecY, RecW, RecH), 1.0f,
                             CanvasImageInterpolation.HighQualityCubic);
            }
        }
Esempio n. 14
0
        private void RenderCustomImage(Color c, double width, double height)
        {
            Debug.WriteLine("Render custom image | Width: " + width + " | Height: " + height);
            double ratio;
            float  x;
            float  y;

            if (width > height)
            {
                //Use height
                ratio = height / 300;
                x     = (float)((width / 2) - (height / 2));
                y     = 0;
            }
            else
            {
                //Use width
                ratio = width / 300;
                y     = (float)((height / 2) - (width / 2));
                x     = 0;
            }

            var effect = new Transform2DEffect
            {
                Source            = UserBitmap,
                InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                TransformMatrix   = Matrix3x2.CreateScale(new Vector2((float)(SZoomF * ratio)))
            };

            CanvasRenderTarget sqRenderTarget = new CanvasRenderTarget(_device, (float)(300 * ratio), (float)(300 * ratio),
                                                                       96);

            PlexibleX = X - 160;
            if (IsManualAdjustSquareImage)
            {
                using (var ds = sqRenderTarget.CreateDrawingSession())
                {
                    //Clear the color
                    ds.Clear(c);

                    //Draw the user image to target
                    ds.DrawImage(effect, (float)(SX * ratio), (float)(SY * ratio),
                                 new Rect(SRecX, SRecY, SRecW * ratio, SRecH * ratio), 1.0f,
                                 CanvasImageInterpolation.HighQualityCubic);
                }
            }
            else
            {
                using (var ds = sqRenderTarget.CreateDrawingSession())
                {
                    //Clear the color
                    ds.Clear(c);

                    //Draw the user image to target
                    ds.DrawImage(effect, (float)(PlexibleX * ratio), (float)(Y * ratio),
                                 new Rect(RecX, RecY, RecW * ratio, RecH * ratio), 1.0f, CanvasImageInterpolation.HighQualityCubic);
                }
            }

            CustomRenderTarget = new CanvasRenderTarget(_device, (float)width, (float)height, 96);
            using (var ds = CustomRenderTarget.CreateDrawingSession())
            {
                ds.Clear(c);
                ds.DrawImage(sqRenderTarget, x, y,
                             new Rect(SRecX, SRecY, (float)(300 * ratio), (float)(300 * ratio)), 1.0f,
                             CanvasImageInterpolation.HighQualityCubic);
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Creates a scale matrix from the given vector scale with an offset from the given center point.
 /// </summary>
 /// <param name="scales">The scale to use.</param>
 /// <param name="centerPoint">The center offset.</param>
 /// <returns>A scaling matrix.</returns>
 public static Matrix3x2 CreateScale(SizeF scales, PointF centerPoint) => Matrix3x2.CreateScale(scales, centerPoint);
Esempio n. 16
0
        async Task GenerateIcon(AppInfo appInfo, IconInfo iconInfo, StorageFolder folder)
        {
            // Draw the icon image into a command list.
            var commandList = new CanvasCommandList(device);

            using (var ds = commandList.CreateDrawingSession())
            {
                appInfo.DrawIconImage(ds, iconInfo);
            }

            ICanvasImage iconImage = commandList;

            // Rasterize into a rendertarget.
            var renderTarget = new CanvasRenderTarget(device, iconInfo.Width, iconInfo.Height, 96);

            using (var ds = renderTarget.CreateDrawingSession())
            {
                // Initialize with the appropriate background color.
                ds.Clear(iconInfo.TransparentBackground ? Colors.Transparent : appInfo.BackgroundColor);

                // Work out where to position the icon image.
                var imageBounds = iconImage.GetBounds(ds);

                imageBounds.Height *= 1 + iconInfo.BottomPadding;

                float scaleUpTheSmallerIcons = Math.Max(1, 1 + (60f - iconInfo.Width) / 50f);

                float imageScale = appInfo.ImageScale * scaleUpTheSmallerIcons;

                var transform = Matrix3x2.CreateTranslation((float)-imageBounds.X, (float)-imageBounds.Y) *
                                Utils.GetDisplayTransform(renderTarget.Size.ToVector2(), new Vector2((float)imageBounds.Width, (float)imageBounds.Height)) *
                                Matrix3x2.CreateScale(imageScale, renderTarget.Size.ToVector2() / 2);

                if (iconInfo.Monochrome)
                {
                    // Optionally convert to monochrome.
                    iconImage = new DiscreteTransferEffect
                    {
                        Source = new Transform2DEffect
                        {
                            Source = new LuminanceToAlphaEffect {
                                Source = iconImage
                            },
                            TransformMatrix = transform
                        },

                        RedTable   = new float[] { 1 },
                        GreenTable = new float[] { 1 },
                        BlueTable  = new float[] { 1 },
                        AlphaTable = new float[] { 0, 1 }
                    };
                }
                else
                {
                    ds.Transform = transform;

                    // Optional shadow effect.
                    if (appInfo.AddShadow)
                    {
                        var shadow = new ShadowEffect
                        {
                            Source     = iconImage,
                            BlurAmount = 12,
                        };

                        ds.DrawImage(shadow);
                    }
                }

                // draw the main icon image.
                ds.DrawImage(iconImage);
            }

            // Save to a file.
            using (var stream = await folder.OpenStreamForWriteAsync(iconInfo.Filename, CreationCollisionOption.ReplaceExisting))
            {
                await renderTarget.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Png);
            }
        }
Esempio n. 17
0
 /// <summary>
 /// Creates a scale matrix that scales uniformly with the given scale with an offset from the given center.
 /// </summary>
 /// <param name="scale">The uniform scale to use.</param>
 /// <param name="centerPoint">The center offset.</param>
 /// <returns>A scaling matrix.</returns>
 public static Matrix3x2 CreateScale(float scale, PointF centerPoint) => Matrix3x2.CreateScale(scale, centerPoint);
 /// <summary>
 /// Applies transformation on the current pass.
 /// </summary>
 /// <param name="transform">The transform.</param>
 public void SetTransform(GraphTransform transform)
 {
     _session.Transform = Matrix3x2.CreateTranslation(transform.TranslateX / transform.ScaleX, transform.TranslateY / transform.ScaleY) * Matrix3x2.CreateScale(transform.ScaleX, transform.ScaleY);
 }
        public void ControlPaint_DrawBorder_Inset_ControlColor_Rendering()
        {
            using var emf = new EmfScope();
            DeviceContextState state = new DeviceContextState(emf);

            using Graphics graphics = Graphics.FromHdc((IntPtr)emf.HDC);

            Rectangle bounds = new Rectangle(10, 10, 10, 10);

            ControlPaint.DrawBorder(graphics, bounds, SystemColors.Control, ButtonBorderStyle.Inset);

            // For whatever reason GDI+ renders as polylines scaled 16x with a 1/16th world transform applied.
            // For test readability we'll transform the points from our coordinates to the logical coordinates.
            Matrix3x2 oneSixteenth = Matrix3x2.CreateScale(0.0625f);
            Matrix3x2 times16      = Matrix3x2.CreateScale(16.0f);

            // This is the default pen style GDI+ renders polylines with
            Gdi32.PS penStyle = Gdi32.PS.SOLID | Gdi32.PS.JOIN_ROUND | Gdi32.PS.COSMETIC | Gdi32.PS.ENDCAP_FLAT
                                | Gdi32.PS.JOIN_MITER | Gdi32.PS.GEOMETRIC;

            emf.Validate(
                state,
                // Top
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 10, 10, 19, 10),
                    State.Pen(16, ControlPaint.DarkDark(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),
                // Left
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 10, 10, 10, 19),
                    State.Pen(16, ControlPaint.DarkDark(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),
                // Bottom
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 10, 19, 19, 19),
                    State.Pen(16, ControlPaint.LightLight(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),
                // Right
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 19, 10, 19, 19),
                    State.Pen(16, ControlPaint.LightLight(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),
                // Top inset
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 11, 11, 18, 11),
                    State.Pen(16, ControlPaint.Light(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),
                // Left inset
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 11, 11, 11, 18),
                    State.Pen(16, ControlPaint.Light(SystemColors.Control), penStyle),
                    State.Transform(oneSixteenth)),

                // The bottom/right insets are only drawn if the original color was SystemColors.Control.

                // Bottom inset
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 11, 18, 18, 18),
                    State.Pen(16, SystemColors.ControlLight, penStyle),
                    State.Transform(oneSixteenth)),
                // Right inset
                Validate.Polyline16(
                    bounds: null,
                    PointArray(times16, 18, 11, 18, 18),
                    State.Pen(16, SystemColors.ControlLight, penStyle),
                    State.Transform(oneSixteenth))
                );
        }
Esempio n. 20
0
        void DrawStuff(CanvasDrawingSession ds)
        {
            int horizontalLimit = (int)m_canvasControl.ActualWidth;
            int verticalLimit   = (int)m_canvasControl.ActualHeight;

            DrawnContentType drawnContentType = (DrawnContentType)m_drawnContentTypeCombo.SelectedValue;

            ds.Clear(NextRandomColor());

            Vector2 point;
            float   radiusX;
            float   radiusY;

            Random random = new Random();

            m_canvasSwapChainPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            switch (drawnContentType)
            {
            case DrawnContentType.Clear_Only:
                break;

            case DrawnContentType.Bitmap:
                if (m_bitmap_tiger != null)
                {
                    ds.DrawImage(m_bitmap_tiger, NextRandomPoint(horizontalLimit, verticalLimit).ToVector2());
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.Rectangle_Filled:
                Point bound0 = NextRandomPoint(horizontalLimit, verticalLimit);
                Point bound1 = NextRandomPoint(horizontalLimit, verticalLimit);

                m_linearGradientBrush.StartPoint = bound0.ToVector2();
                m_linearGradientBrush.EndPoint   = bound1.ToVector2();

                ds.FillRectangle(
                    new Rect(bound0, bound1),
                    m_linearGradientBrush);

                break;

            case DrawnContentType.Ellipse_Fill:
                NextRandomEllipse(horizontalLimit, verticalLimit, out point, out radiusX, out radiusY);
                ds.FillEllipse(
                    point, radiusX, radiusY,
                    NextRandomColor());
                break;

            case DrawnContentType.Circle_Fill:
                ds.FillCircle(
                    NextRandomPoint(horizontalLimit, verticalLimit).ToVector2(),
                    100,
                    NextRandomColor());
                break;

            case DrawnContentType.Text:
                var p     = NextRandomPoint(horizontalLimit, verticalLimit);
                var x     = (float)p.X;
                var y     = (float)p.Y;
                var color = NextRandomColor();
                ds.DrawLine(new Vector2(x, 0), new Vector2(x, verticalLimit), color);
                ds.DrawLine(new Vector2(0, y), new Vector2(horizontalLimit, y), color);
                ds.DrawText(
                    "Centered",
                    p.ToVector2(),
                    color,
                    new CanvasTextFormat()
                {
                    FontSize           = 18,
                    VerticalAlignment  = CanvasVerticalAlignment.Center,
                    ParagraphAlignment = ParagraphAlignment.Center
                });

                var r = NextRandomRect(horizontalLimit, verticalLimit);
                ds.DrawRectangle(r, color);
                ds.DrawText(
                    m_quiteLongText,
                    r,
                    NextRandomColor(),
                    new CanvasTextFormat()
                {
                    FontFamily         = "Comic Sans MS",
                    FontSize           = 18,
                    ParagraphAlignment = ParagraphAlignment.Justify,
                    Options            = CanvasDrawTextOptions.Clip
                });
                break;

            case DrawnContentType.ImageBrush:
                if (m_bitmap_tiger != null)
                {
                    m_imageBrush.Image   = m_bitmap_tiger;
                    m_imageBrush.ExtendX = (CanvasEdgeBehavior)(m_random.Next(3));
                    m_imageBrush.ExtendY = (CanvasEdgeBehavior)(m_random.Next(3));
                    ds.FillRectangle(new Rect(0, 0, horizontalLimit, verticalLimit), m_imageBrush);
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.OffscreenTarget:
                m_imageBrush.Image   = m_offscreenTarget;
                m_imageBrush.ExtendX = (CanvasEdgeBehavior)(m_random.Next(3));
                m_imageBrush.ExtendY = (CanvasEdgeBehavior)(m_random.Next(3));
                ds.FillRectangle(new Rect(0, 0, horizontalLimit, verticalLimit), m_imageBrush);
                break;

            case DrawnContentType.Gradients:
                Vector2 center = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                m_radialGradientBrush.Center = center;
                float radius = m_random.Next(horizontalLimit / 2);
                m_radialGradientBrush.OriginOffset = new Vector2(radius, radius);
                m_radialGradientBrush.RadiusX      = radius;
                m_radialGradientBrush.RadiusY      = radius;
                ds.FillCircle(center, radius, m_radialGradientBrush);

                Vector2 line0 = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                Vector2 line1 = NextRandomPoint(horizontalLimit, verticalLimit).ToVector2();
                m_linearGradientBrush.StartPoint = line0;
                m_linearGradientBrush.EndPoint   = line1;
                float thickness = m_random.Next(horizontalLimit / 2);
                ds.DrawLine(line0, line1, m_linearGradientBrush, thickness);
                break;

            case DrawnContentType.AlternateBitmapLoading:
                if (m_bitmap_colorGrids != null)
                {
                    Matrix3x2 scale = Matrix3x2.CreateScale(20);

                    ds.Transform = scale;
                    ds.DrawImage(m_bitmap_colorGrids[0]);

                    ds.Transform = scale * Matrix3x2.CreateTranslation(200, 0);
                    ds.DrawImage(m_bitmap_colorGrids[1]);

                    ds.Transform = scale * Matrix3x2.CreateTranslation(0, 200);
                    ds.DrawImage(m_bitmap_colorGrids[2]);
                }
                else
                {
                    DrawNoBitmapErrorMessage(ds, horizontalLimit / 2, verticalLimit / 2);
                }
                break;

            case DrawnContentType.SwapChainPanel:
                m_canvasSwapChainPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;

                float swapChainWidth  = horizontalLimit * ((float)random.NextDouble() / 2 + 0.5f);
                float swapChainHeight = verticalLimit * ((float)random.NextDouble() / 2 + 0.5f);

                if (m_swapChain == null)
                {
                    m_swapChain = new CanvasSwapChain(ds, swapChainWidth, swapChainHeight);
                    m_canvasSwapChainPanel.SwapChain = m_swapChain;
                }
                else
                {
                    m_swapChain.ResizeBuffers(swapChainWidth, swapChainHeight);
                }

                using (CanvasDrawingSession panelDS = m_swapChain.CreateDrawingSession(NextRandomColor()))
                {
                    panelDS.DrawCircle(swapChainWidth / 2.0f, swapChainHeight / 2.0f, 100.0f, NextRandomColor(), 20.0f);
                }
                m_swapChain.Present();
                break;

            case DrawnContentType.Test_Scene0_Default:
                GeometryTestScene0.DrawGeometryTestScene(ds, TestSceneRenderingType.Default);
                break;

            case DrawnContentType.Test_Scene0_Wireframe:
                GeometryTestScene0.DrawGeometryTestScene(ds, TestSceneRenderingType.Wireframe);
                break;

            case DrawnContentType.Test_Scene1_Default:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Default);
                break;

            case DrawnContentType.Test_Scene1_Randomized:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Randomized);
                break;

            case DrawnContentType.Test_Scene1_Wireframe:
                GeometryTestScene1.DrawGeometryTestScene(ds, TestSceneRenderingType.Wireframe);
                break;

            default:
                System.Diagnostics.Debug.Assert(false);     // Unexpected
                break;
            }
        }
Esempio n. 21
0
 /// <summary>
 /// Creates a path translated by the supplied postion
 /// </summary>
 /// <param name="path">The path to translate.</param>
 /// <param name="scale">The amount to scale along both the x and y axis.</param>
 /// <returns>A <see cref="IPath"/> with a translate transform applied.</returns>
 public static IPathCollection Scale(this IPathCollection path, float scale)
 {
     return(path.Transform(Matrix3x2.CreateScale(scale, RectangleF.Center(path.Bounds))));
 }
        protected override void drawChart(CanvasDrawingSession canvas)
        {
            if (chartData != null)
            {
                float fullWidth = (chartWidth / (pickerDelegate.pickerEnd - pickerDelegate.pickerStart));
                float offset    = fullWidth * (pickerDelegate.pickerStart) - HORIZONTAL_PADDING;

                //canvas.save();
                var   transform       = canvas.Transform;
                float transitionAlpha = 1f;
                if (transitionMode == TRANSITION_MODE_PARENT)
                {
                    transitionAlpha = transitionParams.progress > 0.5f ? 0 : 1f - transitionParams.progress * 2f;

                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(1 + 2 * transitionParams.progress, 1f),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }
                else if (transitionMode == TRANSITION_MODE_CHILD)
                {
                    transitionAlpha = transitionParams.progress < 0.3f ? 0 : transitionParams.progress;

                    //canvas.save();
                    canvas.Transform = Matrix3x2.CreateScale(
                        new Vector2(transitionParams.progress, transitionParams.progress),
                        new Vector2(transitionParams.pX, transitionParams.pY)
                        );
                }
                else if (transitionMode == TRANSITION_MODE_ALPHA_ENTER)
                {
                    transitionAlpha = transitionParams.progress;
                }

                for (int k = 0; k < lines.Count; k++)
                {
                    LineViewData line = lines[k];
                    if (!line.enabled && line.alpha == 0)
                    {
                        continue;
                    }

                    int j = 0;

                    int[] y = line.line.y;

                    line.chartPath = new CanvasPathBuilder(canvas);
                    bool first = true;

                    float p;
                    if (chartData.xPercentage.Length < 2)
                    {
                        p = 1f;
                    }
                    else
                    {
                        p = chartData.xPercentage[1] * fullWidth;
                    }

                    int additionalPoints = (int)(HORIZONTAL_PADDING / p) + 1;
                    int localStart       = Math.Max(0, startXIndex - additionalPoints);
                    int localEnd         = Math.Min(chartData.xPercentage.Length - 1, endXIndex + additionalPoints);

                    for (int i = localStart; i <= localEnd; i++)
                    {
                        if (y[i] < 0)
                        {
                            continue;
                        }
                        float xPoint      = chartData.xPercentage[i] * fullWidth - offset;
                        float yPercentage = ((float)y[i] * chartData.linesK[k] - currentMinHeight) / (currentMaxHeight - currentMinHeight);
                        float padding     = line.paint.StrokeWidth / 2f;
                        float yPoint      = getMeasuredHeight() - chartBottom - padding - (yPercentage) * (getMeasuredHeight() - chartBottom - SIGNATURE_TEXT_HEIGHT - padding);

                        if (USE_LINES)
                        {
                            if (j == 0)
                            {
                                line.linesPath[j++] = xPoint;
                                line.linesPath[j++] = yPoint;
                            }
                            else
                            {
                                line.linesPath[j++] = xPoint;
                                line.linesPath[j++] = yPoint;
                                line.linesPath[j++] = xPoint;
                                line.linesPath[j++] = yPoint;
                            }
                        }
                        else
                        {
                            if (first)
                            {
                                first = false;

                                if (drawSteps)
                                {
                                    line.chartPath.BeginFigure(xPoint - (p / 2), yPoint);
                                    line.chartPath.AddLine(xPoint + (p / 2), yPoint);
                                }
                                else
                                {
                                    line.chartPath.BeginFigure(xPoint, yPoint);
                                }
                            }
                            else
                            {
                                if (drawSteps)
                                {
                                    line.chartPath.AddLine(xPoint - (p / 2), yPoint);
                                    line.chartPath.AddLine(xPoint + (p / 2), yPoint);
                                }
                                else
                                {
                                    line.chartPath.AddLine(xPoint, yPoint);
                                }
                            }
                        }
                    }
                    line.chartPath.EndFigure(CanvasFigureLoop.Open);

                    if (endXIndex - startXIndex > 100)
                    {
                        line.paint.StrokeCap = CanvasCapStyle.Square;
                    }
                    else
                    {
                        line.paint.StrokeCap = CanvasCapStyle.Round;
                    }
                    line.paint.A = (byte)(255 * line.alpha * transitionAlpha);
                    if (!USE_LINES)
                    {
                        canvas.DrawGeometry(CanvasGeometry.CreatePath(line.chartPath), line.paint);
                    }
                    //else canvas.drawLines(line.linesPath, 0, j, line.paint);
                }

                //canvas.restore();
                canvas.Transform = transform;
            }
        }
Esempio n. 23
0
 public DefaultSvgRenderer()
 {
     Transform = Matrix3x2.CreateScale(1, 1);
 }
Esempio n. 24
0
        public static async void ExportPngAsync()
        {
            try
            {
                string name = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
                if (await PickFileAsync(name, "PNG Image", new[] { ".png" }) is StorageFile file)
                {
                    CachedFileManager.DeferUpdates(file);

                    var device   = CanvasDevice.GetSharedDevice();
                    var localDpi = 96; //Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi;

                    var canvasH = (float)2048;
                    var canvasW = (float)2048;

                    using (var renderTarget = new CanvasRenderTarget(device, canvasW, canvasH, localDpi))
                    {
                        using (var ds = renderTarget.CreateDrawingSession())
                        {
                            ds.Clear(Colors.Transparent);
                            double d = 2048;

                            var textColor = Colors.White;
                            var fontSize  = (float)d;

                            using (CanvasTextLayout layout = new CanvasTextLayout(device, $"{GlobalTool.SelectedEmoji.Text}", new CanvasTextFormat
                            {
                                FontSize = fontSize,
                                FontFamily = "Segoe UI Emoji",
                                FontStretch = FontStretch.Normal,
                                FontWeight = new FontWeight {
                                    Weight = 1
                                },
                                FontStyle = FontStyle.Normal,
                                HorizontalAlignment = CanvasHorizontalAlignment.Center,
                                Options = CanvasDrawTextOptions.Default
                            }, canvasW, canvasH))
                            {
                                layout.Options = CanvasDrawTextOptions.EnableColorFont;

                                layout.SetTypography(0, 1, new CanvasTypography());

                                var    db    = layout.DrawBounds;
                                double scale = Math.Min(1, Math.Min(canvasW / db.Width, canvasH / db.Height));
                                var    x     = -db.Left + ((canvasW - (db.Width * scale)) / 2d);
                                var    y     = -db.Top + ((canvasH - (db.Height * scale)) / 2d);

                                ds.Transform =
                                    Matrix3x2.CreateTranslation(new Vector2((float)x, (float)y))
                                    * Matrix3x2.CreateScale(new Vector2((float)scale));

                                ds.DrawTextLayout(layout, new Vector2(0), textColor);
                            }
                        }

                        using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            fileStream.Size = 0;
                            await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
                        }
                    }


                    await CachedFileManager.CompleteUpdatesAsync(file);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        private void SkiaManager_BeforePaint(object sender, SkiaSharp.SKCanvas e)
        {
            var skiaManager = sender as SkiaManager;

            SKMatrix.MakeTranslation(0, e.LocalClipBounds.Height);
            var matrix = skiaManager.SketchSpaceToCanvasSpaceMatrix;

            Sketch.Width  = SketchSize.X;
            Sketch.Height = SketchSize.Y;

            SKPoint sketchSize = new SKPoint(Sketch.Width, Sketch.Height);

            //matrix.SetScaleTranslate(1f, -1f, e.LocalClipBounds.Width / 2, e.LocalClipBounds.Height / 2);

            var sketchRatio    = sketchSize.X / sketchSize.Y;
            var localClipRatio = e.LocalClipBounds.Width / e.LocalClipBounds.Height;
            var xFactor        = e.LocalClipBounds.Width / sketchSize.X;
            var yFactor        = e.LocalClipBounds.Height / sketchSize.Y;

            if (localClipRatio > sketchRatio)
            {
                xFactor = yFactor;
            }
            else
            {
                yFactor = xFactor;
            }
            var xTranslate = e.LocalClipBounds.MidX - (xFactor * sketchSize.X) / 2;
            var yTranslate = e.LocalClipBounds.Height - (e.LocalClipBounds.MidY - (yFactor * sketchSize.Y) / 2);

            matrix.SetScaleTranslate(xFactor, -yFactor, xTranslate, yTranslate);
            skiaManager.SketchSpaceToCanvasSpaceMatrix = matrix;

            Matrix3x2 epxToPx         = Matrix3x2.CreateScale(1);
            Matrix3x2 pxToSketchSpace = Matrix3x2.Multiply(Matrix3x2.CreateTranslation(-xTranslate, -yTranslate), Matrix3x2.CreateScale(1 / xFactor, -1 / yFactor));

            SketchInputManager.InputSpaceToSketchSpaceMatrix = Matrix3x2.Multiply(epxToPx, pxToSketchSpace);
        }
Esempio n. 26
0
 /// <summary>
 /// Creates a scale matrix that is offset by a given center point.
 /// </summary>
 /// <param name="xScale">Value to scale by on the X-axis.</param>
 /// <param name="yScale">Value to scale by on the Y-axis.</param>
 /// <param name="centerPoint">The center point.</param>
 /// <returns>A scaling matrix.</returns>
 public static Matrix3x2 CreateScale(float xScale, float yScale, PointF centerPoint) => Matrix3x2.CreateScale(xScale, yScale, centerPoint);
 /// <summary>
 /// Appends a scale matrix from the given vector scale.
 /// </summary>
 /// <param name="scales">The horizontal and vertical scale.</param>
 /// <returns>The <see cref="AffineTransformBuilder"/>.</returns>
 public AffineTransformBuilder AppendScale(Vector2 scales)
 => this.AppendMatrix(Matrix3x2.CreateScale(scales));
Esempio n. 28
0
 /// <summary>
 /// Creates a scale matrix from the given vector scale.
 /// </summary>
 /// <param name="scales">The scale to use.</param>
 /// <returns>A scaling matrix.</returns>
 public static Matrix3x2 CreateScale(SizeF scales) => Matrix3x2.CreateScale(scales);
Esempio n. 29
0
        public void Matrix3x2CreateScaleCenterTest2()
        {
            float   scale  = 5;
            Vector2 center = new Vector2(23, 42);

            Matrix3x2 scaleAroundZero         = Matrix3x2.CreateScale(scale, Vector2.Zero);
            Matrix3x2 scaleAroundZeroExpected = Matrix3x2.CreateScale(scale);

            Assert.True(MathHelper.Equal(scaleAroundZero, scaleAroundZeroExpected));

            Matrix3x2 scaleAroundCenter         = Matrix3x2.CreateScale(scale, center);
            Matrix3x2 scaleAroundCenterExpected = Matrix3x2.CreateTranslation(-center) * Matrix3x2.CreateScale(scale) * Matrix3x2.CreateTranslation(center);

            Assert.True(MathHelper.Equal(scaleAroundCenter, scaleAroundCenterExpected));
        }
Esempio n. 30
0
        public void DisplaySquarePreview()
        {
            if (!IsManualAdjustSquareImage)
            {
                SX = X - 160;
                SY = Y;

                SRecX = RecX;
                SRecY = RecY;
                SRecW = RecW;
                SRecH = RecH;

                SZoomF = ZoomF;

                SMaxWidth  = MaxWidth;
                SMaxHeight = MaxHeight;
            }

            if (File == null)
            {
                return;
            }

            //Get current color
            Color c = new Color
            {
                A = (byte)BackgroundVm.ColorBackgroundVm.A,
                R = (byte)BackgroundVm.ColorBackgroundVm.R,
                G = (byte)BackgroundVm.ColorBackgroundVm.G,
                B = (byte)BackgroundVm.ColorBackgroundVm.B
            };

            if (SIsCaculation)
            {
                //Send message to output
                Debug.WriteLine("Re caculate param");

                if (UserBitmap.SizeInPixels.Width <= UserBitmap.SizeInPixels.Height)
                {
                    SZoomF = (float)300 / UserBitmap.SizeInPixels.Height;
                }
                else
                {
                    SZoomF = (float)300 / UserBitmap.SizeInPixels.Width;
                }

                SX = 150 - ((UserBitmap.SizeInPixels.Width * SZoomF) / 2);
                SY = 150 - ((UserBitmap.SizeInPixels.Height * SZoomF) / 2);

                SIsCaculation = false;
            }

            SRecW = UserBitmap.SizeInPixels.Width * SZoomF;
            SRecH = UserBitmap.SizeInPixels.Height * SZoomF;

            var effect = new Transform2DEffect
            {
                Source            = UserBitmap,
                InterpolationMode = CanvasImageInterpolation.HighQualityCubic,
                TransformMatrix   = Matrix3x2.CreateScale(new Vector2(SZoomF))
            };

            //Render target: Main render
            SRenderTarget = new CanvasRenderTarget(_device, 300, 300, 96);
            using (var ds = SRenderTarget.CreateDrawingSession())
            {
                //Clear the color
                ds.Clear(c);

                //Draw transperent bitmap
                ds.DrawImage(_transperentBitmap, 0, 0, new Rect(0, 0, 300, 300), 1.0f);

                //Fill the rectangle with color
                ds.FillRectangle(0, 0, 300, 300, c);

                //Draw the user image to target
                ds.DrawImage(effect, SX, SY, new Rect(SRecX, SRecY, SRecW, SRecH), 1.0f,
                             CanvasImageInterpolation.HighQualityCubic);
            }
        }