Beispiel #1
0
 public Player(string name, Color color, float scale, string pos)
 {
     Name = name;
     Color = new SolidColorBrush(color);
     Scale = scale;
     Pos = pos;
 }
 public CustomTextRenderer(Direct2DFactory factory, WindowRenderTarget renderTarget, SolidColorBrush outlineBrush, BitmapBrush fillBrush)
 {
     _factory = factory;
     _renderTarget = renderTarget;
     _outlineBrush = outlineBrush;
     _fillBrush = fillBrush;
 }
Beispiel #3
0
        /// <summary>
        /// In a derived class, implements logic to initialize the sample.
        /// </summary>
        protected override void OnInitialize() {
            DeviceSettings2D settings = new DeviceSettings2D {
                Width = WindowWidth,
                Height = WindowHeight
            };

            InitializeDevice(settings);
            geometry = new PathGeometry(Context2D.RenderTarget.Factory);
            using (GeometrySink sink = geometry.Open()) {
                PointF p0 = new PointF(0.50f * WindowWidth, 0.25f * WindowHeight);
                PointF p1 = new PointF(0.75f * WindowWidth, 0.75f * WindowHeight);
                PointF p2 = new PointF(0.25f * WindowWidth, 0.75f * WindowHeight);

                sink.BeginFigure(p0, FigureBegin.Filled);
                sink.AddLine(p1);
                sink.AddLine(p2);
                sink.EndFigure(FigureEnd.Closed);

                // Note that Close() and Dispose() are not equivalent like they are for
                // some other IDisposable() objects.
                sink.Close();
            }

            brush = new SolidColorBrush(Context2D.RenderTarget, new Color4(0.93f, 0.40f, 0.08f));
        }
partial         void Initialize()
        {
            Background = new SolidColorBrush(Colors.Transparent);
            Clip = new RectangleGeometry();

            SizeChanged += OnRenderSizeChanged;
        }
        protected internal void ColorChanging(Color color)
        {
            Color = color;
            SolidColorBrush = new SolidColorBrush(Color);

            if (ColorChanged != null)
                ColorChanged(this, Color);
        }
        public void TestSerialization()
        {
            var solidColorBrush = new SolidColorBrush { Color = Colors.Aqua };

            var writer = new StringWriter();
            _serializer.Serialize(writer, solidColorBrush);
            var reader = new StringReader(writer.ToString());

            Assert.AreEqual(solidColorBrush, _serializer.Deserialize(reader));
        }
		public override void OnApplyTemplate()
		{
			WatermarkBrush = new SolidColorBrush(Colors.DarkGray);
#endif

			base.OnApplyTemplate();
			_textBox = (TextBox)GetTemplateChild("_textBox");
			_textBox.GotFocus += TextBoxOnGotFocus;
			_textBox.LostFocus += TextBoxOnLostFocus;
			_textBox.TextChanged += TextBoxOnTextChanged;

			originalForeground = _textBox.Foreground;

			UpdateText();
		}
        /// <summary>
        /// Creates a new instance of VpaidImageAdPlayer.
        /// </summary>
        /// <param name="skippableOffset">The position in the ad at which the ad can be skipped. If null, the ad cannot be skipped.</param>
        /// <param name="suggestedDuration">The duration of the ad. If not specified, the ad is closed when the next ad is played.</param>
        /// <param name="clickThru">The Uri to navigate to when the ad is clicked or tapped. Can be null of no action should take place.</param>
        public VpaidImageAdPlayer(FlexibleOffset skippableOffset, TimeSpan? suggestedDuration, Uri clickThru)
        {
            IsHitTestVisible = false;
            image = new Image();
            Background = new SolidColorBrush(Colors.Transparent);
            image.Stretch = Stretch.None;
            Opacity = 0;
            State = AdState.None;
            AdLinear = false;

            SkippableOffset = skippableOffset;
            SuggestedDuration = suggestedDuration;
            ClickThru = clickThru;
            this.NavigateUri = ClickThru;
        }
        /**
         * Render with or without texture
         **/
        protected override void _render()
        {
            if (this._bitmap == null)
            {
                // Render in solid color
                if (_brush == null)
                    _brush = new SolidColorBrush(Device.RenderTarget, Color);

                Device.RenderTarget.FillRectangle(_brush, _rectangle);

                return;
            }

            if (this._d2dBitmap == null)
            {
                // Load the texture
                var bitmapData = this._bitmap.LockBits(
                    new Rectangle(new Point(0, 0), this._bitmap.Size),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb
                );
                var dataStream = new SlimDX.DataStream(
                    bitmapData.Scan0,
                    bitmapData.Stride * bitmapData.Height,
                    true,
                    false
                );
                var d2dPixelFormat = new SlimDX.Direct2D.PixelFormat(
                    SlimDX.DXGI.Format.B8G8R8A8_UNorm,
                    SlimDX.Direct2D.AlphaMode.Premultiplied
                );
                var d2dBitmapProperties = new SlimDX.Direct2D.BitmapProperties();
                d2dBitmapProperties.PixelFormat = d2dPixelFormat;

                _d2dBitmap = new SlimDX.Direct2D.Bitmap(
                    Device.RenderTarget,
                    new Size(this._bitmap.Width, this._bitmap.Height),
                    dataStream,
                    bitmapData.Stride,
                    d2dBitmapProperties
                );
                this._bitmap.UnlockBits(bitmapData);
            }

            // Render the texture
            Device.RenderTarget.DrawBitmap(_d2dBitmap, _rectangle);
        }
        /// <summary>
        /// Creates a new instance of VpaidVideoAdPlayer.
        /// </summary>
        /// <param name="skippableOffset">The position in the ad at which the ad can be skipped. If null, the ad cannot be skipped.</param>
        /// <param name="maxDuration">The max duration of the ad. If not specified, the length of the video is assumed.</param>
        /// <param name="clickThru">The Uri to navigate to when the ad is clicked or tapped. Can be null of no action should take place.</param>
        public VpaidVideoAdPlayer(FlexibleOffset skippableOffset, TimeSpan? maxDuration, Uri clickThru)
        {
            IsHitTestVisible = false;
            mediaElement = new MediaElement();
            Background = new SolidColorBrush(Colors.Black);
#if !WINDOWS80
            Opacity = 0.01; // HACK: Win8.1 won't load the video if opacity = 0
#else
            Opacity = 0;
#endif
            State = AdState.None;
            AdLinear = true;

            SkippableOffset = skippableOffset;
            MaxDuration = maxDuration;
            this.NavigateUri = clickThru;
        }
Beispiel #11
0
        /// <summary>
        /// This method creates the render target and all associated D2D and DWrite resources
        /// </summary>
        void CreateDeviceResources()
        {
            // Only calls if resources have not been initialize before
            if (renderTarget == null)
            {
                // The text format
                textFormat = dwriteFactory.CreateTextFormat("Bodoni MT", 24, DWrite.FontWeight.Normal, DWrite.FontStyle.Italic, DWrite.FontStretch.Normal);

                // Create the render target
                SizeU size = new SizeU((uint)host.ActualWidth, (uint)host.ActualHeight);
                RenderTargetProperties props = new RenderTargetProperties();
                HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties(host.Handle, size, PresentOptions.None);
                renderTarget = d2dFactory.CreateHwndRenderTarget(props, hwndProps);

                // A black brush to be used for drawing text
                ColorF cf = new ColorF(0, 0, 0, 1);
                blackBrush = renderTarget.CreateSolidColorBrush(cf);

                // Create a linear gradient.
                GradientStop[] stops = 
                { 
                    new GradientStop(1, new ColorF(1f, 0f, 0f, 0.25f)),
                    new GradientStop(0, new ColorF(0f, 0f, 1f, 1f))
                };

                GradientStopCollection pGradientStops = renderTarget.CreateGradientStopCollection(stops, Gamma.Linear, ExtendMode.Wrap);
                LinearGradientBrushProperties gradBrushProps = new LinearGradientBrushProperties(new Point2F(50, 25), new Point2F(25, 50));

                linearGradientBrush = renderTarget.CreateLinearGradientBrush(gradBrushProps, pGradientStops);

                gridPatternBitmapBrush = CreateGridPatternBrush(renderTarget);

                solidBrush1 = renderTarget.CreateSolidColorBrush(new ColorF(0.3F, 0.5F, 0.65F, 0.25F));
                solidBrush2 = renderTarget.CreateSolidColorBrush(new ColorF(0.0F, 0.0F, 0.65F, 0.5F));
                solidBrush3 = renderTarget.CreateSolidColorBrush(new ColorF(0.9F, 0.5F, 0.3F, 0.75F));

                // Create a linear gradient.
                stops[0] = new GradientStop(1, new ColorF(0f, 0f, 0f, 0.25f));
                stops[1] = new GradientStop(0, new ColorF(1f, 1f, 0.2f, 1f));
                GradientStopCollection radiantGradientStops = renderTarget.CreateGradientStopCollection(stops, Gamma.Linear, ExtendMode.Wrap);

                RadialGradientBrushProperties radialBrushProps = new RadialGradientBrushProperties(new Point2F(25, 25), new Point2F(0, 0), 10, 10);
                radialGradientBrush = renderTarget.CreateRadialGradientBrush(radialBrushProps, radiantGradientStops);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Renders a UI control into an image.
        /// </summary>
        /// <param name="control"></param>
        /// <param name="isWideTile"></param>
        /// <returns></returns>
        public static void CreateImage(UIElement control, string imagePath, int width, int height, SolidColorBrush tileBackgroundColor)
        {
            // 1. Setup dimensions for wide tile.
            var bmp = new WriteableBitmap(width, height);

            // 2. Get the name of the background image based on theme            
            var canvas = new System.Windows.Controls.Canvas();
            canvas.Width = width;
            canvas.Height = height;
            canvas.Background = tileBackgroundColor;

            canvas.Children.Add(control);
            canvas.Measure(new Size(width, height));
            canvas.Arrange(new Rect(0, 0, width, height));
            canvas.UpdateLayout();

            // 4. Now output the control as text.
            bmp.Render(canvas, null);
            bmp.Invalidate();

            // 8. Now save the image to local folder.
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // FileMode.Open, FileAccess.Read, FileShare.Read,
                using (var st = new IsolatedStorageFileStream(imagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, store))
                {
                    bmp.SaveJpeg(st, width, height, 0, 100);
                    st.Close();
                }
            }

            try
            {

                bmp = null;
                canvas.Children.Clear();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                Slate.Core.Logging.Logger.Error("Create image", "Warning, attempt to clear up memory for tile image failed", ex);
            }
        }
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Pen"/> class.
 /// </summary>
 /// <param name="color">The stroke color.</param>
 /// <param name="thickness">The stroke thickness.</param>
 /// <param name="dashStyle">The dash style.</param>
 /// <param name="dashCap">The dash cap.</param>
 /// <param name="startLineCap">The start line cap.</param>
 /// <param name="endLineCap">The end line cap.</param>
 /// <param name="lineJoin">The line join.</param>
 /// <param name="miterLimit">The miter limit.</param>
 public Pen(
     uint color, 
     double thickness = 1.0,
     DashStyle dashStyle = null, 
     PenLineCap dashCap = PenLineCap.Flat, 
     PenLineCap startLineCap = PenLineCap.Flat,
     PenLineCap endLineCap = PenLineCap.Flat, 
     PenLineJoin lineJoin = PenLineJoin.Miter, 
     double miterLimit = 10.0)
 {
     Brush = new SolidColorBrush(color);
     Thickness = thickness;
     StartLineCap = startLineCap;
     EndLineCap = endLineCap;
     LineJoin = lineJoin;
     MiterLimit = miterLimit;
     DashStyle = dashStyle;
     DashCap = dashCap;
 }
Beispiel #14
0
        public TextRenderTarget(RenderTargetTexture renderTargetTexture)
        {
            var surface = renderTargetTexture.AsSurface();
            var factory2D = new SlimDX.Direct2D.Factory(SlimDX.Direct2D.FactoryType.SingleThreaded);

            var renderTargetProperties = new RenderTargetProperties
            {
                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                Usage = RenderTargetUsage.None,
                HorizontalDpi = 96,
                VerticalDpi = 96,
                MinimumFeatureLevel = FeatureLevel.Direct3D10,
                Type = RenderTargetType.Default
            };

            mRenderTarget = RenderTarget.FromDXGI(factory2D, surface,
                renderTargetProperties);

            mBrush = new SolidColorBrush(mRenderTarget, new Color4(1, 1, 1));

            CreateTextFormat();
        }
        public object InternalConvert(object value, Type targetType, object parameter)
        {
            if (value == null)
            {
                return null;
            }

            string colorName = value.ToString();
            SolidColorBrush scb = new SolidColorBrush();
            switch (colorName as string)
            {
                case "Magenta":
                    scb.Color = Colors.Magenta;
                    return scb;
                case "Purple":
                    scb.Color = Colors.Purple;
                    return scb;
                case "Brown":
                    scb.Color = Colors.Brown;
                    return scb;
                case "Orange":
                    scb.Color = Colors.Orange;
                    return scb;
                case "Blue":
                    scb.Color = Colors.Blue;
                    return scb;
                case "Red":
                    scb.Color = Colors.Red;
                    return scb;
                case "Yellow":
                    scb.Color = Colors.Yellow;
                    return scb;
                case "Green":
                    scb.Color = Colors.Green;
                    return scb;
                default:
                    return null;
            }
        }
        public MapGraticule()
        {
            IsHitTestVisible = false;
            Stroke = new SolidColorBrush(Color.FromArgb(127, 0, 0, 0));

            path = new Path
            {
                Data = new PathGeometry()
            };

            path.SetBinding(Shape.StrokeProperty, new Binding
            {
                Source = this,
                Path = new PropertyPath("Stroke")
            });

            path.SetBinding(Shape.StrokeThicknessProperty, new Binding
            {
                Source = this,
                Path = new PropertyPath("StrokeThickness")
            });

            Children.Add(path);
        }
Beispiel #17
0
        public AppItemViewModel(IAudioMixerViewModelCallback callback, EarTrumpetAudioSessionModelGroup sessions)
        {
            _sessions = sessions;
            // select a session at random as sndvol does.
            var session = _sessions.Sessions.First();

            IconHeight = IconWidth = 24;
            SessionId  = session.SessionId;
            ProcessId  = session.ProcessId;
            ExeName    = GetExeName(session.DisplayName);
            IsDesktop  = session.IsDesktop;

            _volume = Convert.ToInt32(Math.Round((session.Volume * 100),
                                                 MidpointRounding.AwayFromZero));
            _isMuted  = session.IsMuted;
            _callback = callback;

            if (session.IsDesktop)
            {
                try
                {
                    if (Path.GetExtension(session.IconPath) == ".dll")
                    {
                        Icon = IconService.GetIconFromFileAsImageSource(session.IconPath);
                    }
                    else
                    {
                        // override for SpeechRuntime.exe (Repo -> HEY CORTANA)
                        if (session.IconPath.ToLowerInvariant().Contains("speechruntime.exe"))
                        {
                            var sysType = Environment.Is64BitOperatingSystem ? "SysNative" : "System32";
                            Icon = IconService.GetIconFromFileAsImageSource(Path.Combine("%windir%", sysType, "Speech\\SpeechUX\\SpeechUXWiz.exe"), 0);
                        }
                        else
                        {
                            Icon = System.Drawing.Icon.ExtractAssociatedIcon(session.IconPath).ToImageSource();
                        }
                    }
                }
                catch
                {
                    // ignored
                }
                if (Icon == null)
                {
                    Background = new SolidColorBrush(AccentColorService.GetColorByTypeName("ImmersiveSystemAccent"));
                }
                else
                {
                    Background = new SolidColorBrush(Colors.Transparent);
                }
            }
            else
            {
                if (File.Exists(session.IconPath)) //hack until we invoke the resource manager correctly.
                {
                    Icon = new BitmapImage(new Uri(session.IconPath));
                }
                Background = new SolidColorBrush(AccentColorService.FromABGR(session.BackgroundColor));
            }
        }
Beispiel #18
0
        private static Brush BrushForColor(String colorName)
        {
            if (colorName == null) return null;

            if (brushCache == null)
            {
                brushCache = new Dictionary<string, Brush> {
                        { "black",     new SolidColorBrush(Colors.Black)     },
                        { "white",     new SolidColorBrush(Colors.White)     },
                        { "lightgray", new SolidColorBrush(Colors.LightGray) },
                        { "yellow",    new SolidColorBrush(Colors.Yellow)    },
                        { "none",      null                                  },
                    };
            }

            Brush ret = null;
            if (brushCache.TryGetValue(colorName, out ret))
            {
                return ret;
            }
            else
            {
                if (colorName.StartsWith("#"))
                {
                    string opacityPart = (colorName.Length == 7 ? "FF" : colorName.Substring(1, 2));
                    string colorPart = colorName.Substring((colorName.Length == 7 ? 1 : 3), 6);
                    byte a = (byte)Convert.ToInt32(opacityPart, 16);
                    byte r = (byte)Convert.ToInt32(colorPart.Substring(0, 2), 16);
                    byte g = (byte)Convert.ToInt32(colorPart.Substring(2, 2), 16);
                    byte b = (byte)Convert.ToInt32(colorPart.Substring(4, 2), 16);
                    Color c = Color.FromArgb(a, r, g, b);
                    var scb = new SolidColorBrush(c);
                    brushCache.Add(colorName, scb);
                    return scb;
                }
                throw new ArgumentOutOfRangeException("Color not supported: " + colorName);
            }
        }
        /// <summary>Arranges the contents of a <see cref="T:System.Windows.Controls.Border" /> element.</summary>
        /// <param name="finalSize">The <see cref="T:System.Windows.Size" /> this element uses to arrange its child element.</param>
        /// <returns>The <see cref="T:System.Windows.Size" /> that represents the arranged size of this <see cref="T:System.Windows.Controls.Border" /> element and its child element.</returns>
        // Token: 0x06004265 RID: 16997 RVA: 0x0012F998 File Offset: 0x0012DB98
        protected override Size ArrangeOverride(Size finalSize)
        {
            Thickness borderThickness = this.BorderThickness;

            if (base.UseLayoutRounding && !FrameworkAppContextSwitches.DoNotApplyLayoutRoundingToMarginsAndBorderThickness)
            {
                DpiScale dpi = base.GetDpi();
                borderThickness = new Thickness(UIElement.RoundLayoutValue(borderThickness.Left, dpi.DpiScaleX), UIElement.RoundLayoutValue(borderThickness.Top, dpi.DpiScaleY), UIElement.RoundLayoutValue(borderThickness.Right, dpi.DpiScaleX), UIElement.RoundLayoutValue(borderThickness.Bottom, dpi.DpiScaleY));
            }
            Rect      rect  = new Rect(finalSize);
            Rect      rect2 = Border.HelperDeflateRect(rect, borderThickness);
            UIElement child = this.Child;

            if (child != null)
            {
                Rect finalRect = Border.HelperDeflateRect(rect2, this.Padding);
                child.Arrange(finalRect);
            }
            CornerRadius cornerRadius = this.CornerRadius;
            Brush        borderBrush  = this.BorderBrush;
            bool         flag         = Border.AreUniformCorners(cornerRadius);

            this._useComplexRenderCodePath = !flag;
            if (!this._useComplexRenderCodePath && borderBrush != null)
            {
                SolidColorBrush solidColorBrush = borderBrush as SolidColorBrush;
                bool            isUniform       = borderThickness.IsUniform;
                this._useComplexRenderCodePath = (solidColorBrush == null || (solidColorBrush.Color.A < byte.MaxValue && !isUniform) || (!DoubleUtil.IsZero(cornerRadius.TopLeft) && !isUniform));
            }
            if (this._useComplexRenderCodePath)
            {
                Border.Radii   radii          = new Border.Radii(cornerRadius, borderThickness, false);
                StreamGeometry streamGeometry = null;
                if (!DoubleUtil.IsZero(rect2.Width) && !DoubleUtil.IsZero(rect2.Height))
                {
                    streamGeometry = new StreamGeometry();
                    using (StreamGeometryContext streamGeometryContext = streamGeometry.Open())
                    {
                        Border.GenerateGeometry(streamGeometryContext, rect2, radii);
                    }
                    streamGeometry.Freeze();
                    this.BackgroundGeometryCache = streamGeometry;
                }
                else
                {
                    this.BackgroundGeometryCache = null;
                }
                if (!DoubleUtil.IsZero(rect.Width) && !DoubleUtil.IsZero(rect.Height))
                {
                    Border.Radii   radii2          = new Border.Radii(cornerRadius, borderThickness, true);
                    StreamGeometry streamGeometry2 = new StreamGeometry();
                    using (StreamGeometryContext streamGeometryContext2 = streamGeometry2.Open())
                    {
                        Border.GenerateGeometry(streamGeometryContext2, rect, radii2);
                        if (streamGeometry != null)
                        {
                            Border.GenerateGeometry(streamGeometryContext2, rect2, radii);
                        }
                    }
                    streamGeometry2.Freeze();
                    this.BorderGeometryCache = streamGeometry2;
                }
                else
                {
                    this.BorderGeometryCache = null;
                }
            }
            else
            {
                this.BackgroundGeometryCache = null;
                this.BorderGeometryCache     = null;
            }
            return(finalSize);
        }
 public CustomTextRenderer(Direct2DFactory factory, WindowRenderTarget renderTarget, SolidColorBrush outlineBrush, BitmapBrush fillBrush)
 {
     _factory      = factory;
     _renderTarget = renderTarget;
     _outlineBrush = outlineBrush;
     _fillBrush    = fillBrush;
 }
Beispiel #21
0
        public static void Init(RenderTarget renderTarget)
        {
            // Generate common brushes
            DefaultBrushes = new Brush[DefaultColors.Length];
            for (int i = 0; i < DefaultColors.Length; i++)
                DefaultBrushes[i] = new SolidColorBrush(renderTarget, DefaultColors[i]);
            ChannelBrushes = new Brush[ChannelColors.Length];
            for (int i = 0; i < ChannelColors.Length; i++)
                ChannelBrushes[i] = new SolidColorBrush(renderTarget, ChannelColors[i]);

            // Generate common gradients
            KeyboardGradient = new LinearGradientBrush(renderTarget,
                new GradientStopCollection(renderTarget, new[] {
                    new GradientStop()
                    { Color = new Color4(Color.White),Position = 0 },
                    new GradientStop()
                    { Color = new Color4(Color.DarkGray), Position = 1 }
                }),
                new LinearGradientBrushProperties()
                {
                    StartPoint = new PointF(0, renderTarget.Size.Height),
                    EndPoint = new PointF(0, renderTarget.Size.Height - KEY_HEIGHT)
                });
            BackgroundGradient = new LinearGradientBrush(renderTarget,
                new GradientStopCollection(renderTarget, new[] {
                    new GradientStop()
                    { Color = Color.Black, Position = 1f },
                    new GradientStop()
                    { Color = Color.FromArgb(30, 30, 30), Position = 0f }
                }),
                new LinearGradientBrushProperties()
                {
                    StartPoint = new PointF(0, renderTarget.Size.Height),
                    EndPoint = new PointF(0, 0)
                });
            ChannelGradientBrushes = new LinearGradientBrush[ChannelColors.Length];
            for (int i = 0; i < ChannelGradientBrushes.Length; i++)
            {
                ChannelGradientBrushes[i] = new LinearGradientBrush(renderTarget,
                new GradientStopCollection(renderTarget, new[] {
                    new GradientStop()
                    { Color = ChannelColors[i], Position = 1f },
                    new GradientStop()
                    { Color = ControlPaint.Light(ChannelColors[i], .8f), Position = 0f }
                }),
                new LinearGradientBrushProperties()
                {
                    StartPoint = new PointF(0, renderTarget.Size.Height),
                    EndPoint = new PointF(0, 0)
                });
            }
            // Generate common fonts
            using (var textFactory = new Factory())
            {
                DebugFormat = new TextFormat(textFactory, "Consolas", FontWeight.UltraBold,
                    SlimDX.DirectWrite.FontStyle.Normal, FontStretch.Normal, 18, "en-us");
                HugeFormat = new TextFormat(textFactory, "Consolas", FontWeight.UltraBold,
                   SlimDX.DirectWrite.FontStyle.Normal, FontStretch.Normal, 50, "en-us")
                {
                    TextAlignment = TextAlignment.Center,
                    ParagraphAlignment = ParagraphAlignment.Center
                };
            }
        }
Beispiel #22
0
            private System.Windows.Media.DrawingVisual CreateDrawingVisualProvince(Prov prov, MapColorModes mapColor = MapColorModes.Provs)
            {
                var drawingVisual = new System.Windows.Media.DrawingVisual();
                var dc            = drawingVisual.RenderOpen();

                Brush brush = null;

                if (mapColor == MapColorModes.Provs)
                {
                    var color1 = System.Drawing.Color.FromArgb(prov.Color);
                    brush = new SolidColorBrush(Color.FromRgb(color1.R, color1.G, color1.B));
                }
                else if (mapColor == MapColorModes.Country)
                {
                    var color = Logic.GetCountryColor(prov.Owner);
                    if (color == null)
                    {
                        if (prov.IsLake || prov.IsSea)
                        {
                            var color1 = System.Drawing.Color.FromArgb(prov.Color);
                            brush = new SolidColorBrush(Color.FromRgb(color1.R, color1.G, color1.B));
                        }
                        else if (!prov.IsWaste)
                        {
                            brush = new SolidColorBrush(Colors.LightGray);
                        }
                        else
                        {
                            brush = new SolidColorBrush(Colors.DimGray);
                        }
                    }
                    else
                    {
                        brush = new SolidColorBrush(color.Value);
                    }
                }

                //dc.DrawGeometry(brush,new Pen(Brushes.Red,0),prov.Geometry );

                dc.DrawGeometry(brush, new Pen(brush, 0.45), prov.Geometry);



                //////////////////////////////////////////
                //      FormattedText formattedText = new FormattedText(
                //"11",
                //CultureInfo.GetCultureInfo("en-us"),
                //FlowDirection.LeftToRight,
                //new Typeface(new FontFamily("宋体"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
                //12,
                //Brushes.Red);

                //      Geometry textGeometry = formattedText.BuildGeometry(new Point(0, 0));
                //      var rect = prov.Geometry.Bounds;
                //      var rect1 = textGeometry.Bounds;

                //      var w = rect.Width/rect1.Width;
                //      var h = rect.Height/rect1.Height;

                //      var scale = Math.Min(w, h);
                //      //var max=t
                //      var translateTransform = new ScaleTransform();
                //      //translateTransform.X = -textGeometry.Bounds.Left;
                //      //translateTransform.Y = -textGeometry.Bounds.Top;
                //      dc.PushTransform(translateTransform);
                //      dc.DrawGeometry(Brushes.Red, new Pen(Brushes.Red, 1.0), textGeometry);

                dc.Close();

                return(drawingVisual);
            }
        private void SetupAccountPage()
        {
            ResourceLoader   loader       = ResourceLoader.GetForCurrentView("Salesforce.SDK.Core/Resources");
            SalesforceConfig config       = SDKManager.ServerConfiguration;
            bool             titleMissing = true;

            if (!String.IsNullOrWhiteSpace(config.ApplicationTitle) && config.IsApplicationTitleVisible)
            {
                ApplicationTitle.Visibility = Visibility.Visible;
                ApplicationTitle.Text       = config.ApplicationTitle;
                titleMissing = false;
            }
            else
            {
                ApplicationTitle.Visibility = Visibility.Collapsed;
            }

            if (config.LoginBackgroundLogo != null)
            {
                if (ApplicationLogo.Items != null)
                {
                    ApplicationLogo.Items.Clear();
                    ApplicationLogo.Items.Add(config.LoginBackgroundLogo);
                }
                if (titleMissing)
                {
                    var padding = new Thickness(10, 24, 10, 24);
                    ApplicationLogo.Margin = padding;
                }
            }

            // set background from config
            if (config.LoginBackgroundColor != null)
            {
                var background = new SolidColorBrush((Color)config.LoginBackgroundColor);
                Background = background;
                ServerFlyoutPanel.Background    = background;
                AddServerFlyoutPanel.Background = background;
            }

            // set foreground from config
            if (config.LoginForegroundColor != null)
            {
                var foreground = new SolidColorBrush((Color)config.LoginForegroundColor);
                Foreground = foreground;
                ApplicationTitle.Foreground     = foreground;
                LoginToSalesforce.Foreground    = foreground;
                LoginToSalesforce.BorderBrush   = foreground;
                ChooseConnection.Foreground     = foreground;
                ChooseConnection.BorderBrush    = foreground;
                AddServerFlyoutLabel.Foreground = foreground;
                AddCustomHostBtn.Foreground     = foreground;
                AddCustomHostBtn.BorderBrush    = foreground;
                CancelCustomHostBtn.Foreground  = foreground;
                CancelCustomHostBtn.BorderBrush = foreground;
                ServerFlyoutLabel.Foreground    = foreground;
                AddConnection.Foreground        = foreground;
                AddConnection.BorderBrush       = foreground;
            }

            if (Accounts == null || Accounts.Length == 0)
            {
                _currentState = SingleUserViewState;
                SetLoginBarVisibility(Visibility.Collapsed);
                AuthStorageHelper.WipePincode();
                VisualStateManager.GoToState(this, SingleUserViewState, true);
            }
            else
            {
                _currentState = MultipleUserViewState;
                SetLoginBarVisibility(Visibility.Visible);
                ListTitle.Text = loader.GetString("select_account");
                VisualStateManager.GoToState(this, MultipleUserViewState, true);
            }
            ListboxServers.ItemsSource     = Servers;
            AccountsList.ItemsSource       = Accounts;
            ServerFlyout.Opening          += ServerFlyout_Opening;
            ServerFlyout.Closed           += ServerFlyout_Closed;
            AddServerFlyout.Opened        += AddServerFlyout_Opened;
            AddServerFlyout.Closed        += AddServerFlyout_Closed;
            AccountsList.SelectionChanged += accountsList_SelectionChanged;
            AddConnection.Visibility       = (SDKManager.ServerConfiguration.AllowNewConnections
                ? Visibility.Visible
                : Visibility.Collapsed);
        }
Beispiel #24
0
            /**
             * Constructor
             */
            public EditBox()
            {
                mEditBox = new System.Windows.Controls.TextBox();
                mPasswordBox = new System.Windows.Controls.PasswordBox();
                // by default, the password box is not visible
                mPasswordBox.Visibility = Visibility.Collapsed;

                CreateTheEditBoxGrid();

                View = mEditBoxGrid;

                mIsPasswordMode = false;
                mIsWatermarkMode = false;
                mPlaceholderText = "";

                // by default, the placeholder font color is gray
                mWaterMarkBrush = new SolidColorBrush();
                mWaterMarkBrush.Color = Colors.Gray;

                mForegroundColor = mEditBox.Foreground;

                /**
                 * @brief Sent from the Edit box when it gains focus(the user selects the widget).
                 * The virtual keyboard is shown.
                 *        MAW_EVENT_EDIT_BOX_EDITING_DID_BEGIN
                 */
                mEditBox.GotFocus += new RoutedEventHandler(
                    delegate(object from, RoutedEventArgs args)
                    {
                        /**
                          * simulating the placeholder/watermark
                          */
                        // if watermark present and no user char has been entered
                        if (mIsWatermarkMode && mFirstChar)
                        {
                            // move the cursor to the first position
                            mEditBox.Select(0, 0);
                            SetWatermarkMode(false);
                        }

                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_EDITING_DID_BEGIN);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of mEditBox.GotFocus

                /**
                  * @brief Sent from the Edit box when it loses focus.
                  * The virtual keyboard is hidden.
                  *        MAW_EVENT_EDIT_BOX_EDITING_DID_END
                  */
                mEditBox.LostFocus += new RoutedEventHandler(
                    delegate(object from, RoutedEventArgs args)
                    {
                        /**
                         * simulating the placeholder/watermark
                         */
                        // if no text has been entered by the user than leave the watermark text
                        if (mEditBox.Text.Equals(""))
                        {
                            SetWatermarkMode(true);
                        }

                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_EDITING_DID_END);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of mEditBox.LostFocus

                /**
                  * @brief Sent from the Edit box when the text was changed.
                  *        MAW_EVENT_EDIT_BOX_TEXT_CHANGED
                  */
                mFirstChar = true;
                mEditBox.TextInputStart += new TextCompositionEventHandler(
                    delegate(object from, TextCompositionEventArgs args)
                    {
                        /**
                          * simulating the placeholder/watermark
                          */
                        if (mFirstChar)
                        {
                            SetWatermarkMode(false);
                        }

                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_TEXT_CHANGED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of TextInputStart

                /**
                 * @brief Sent from the Password box when it gains focus(the user selects the widget).
                 * The virtual keyboard is shown.
                 *        MAW_EVENT_EDIT_BOX_EDITING_DID_BEGIN
                 */
                mPasswordBox.GotFocus += new RoutedEventHandler(
                    delegate(object from, RoutedEventArgs args)
                    {
                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_EDITING_DID_BEGIN);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of mPasswordBox.GotFocus

                /**
                  * @brief Sent from the Password box when it loses focus.
                  * The virtual keyboard is hidden.
                  *        MAW_EVENT_EDIT_BOX_EDITING_DID_END
                  */
                mPasswordBox.LostFocus += new RoutedEventHandler(
                    delegate(object from, RoutedEventArgs args)
                    {
                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_EDITING_DID_END);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of mPasswordBox.LostFocus

                /**
                  * @brief Sent from the Password box when the text was changed.
                  *        MAW_EVENT_EDIT_BOX_TEXT_CHANGED
                  */
                mPasswordBox.TextInputStart += new TextCompositionEventHandler(
                    delegate(object from, TextCompositionEventArgs args)
                    {
                        /**
                         * post the event to MoSync runtime
                         */
                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType = 0;
                        const int MAWidgetEventData_widgetHandle = 4;
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_EDIT_BOX_TEXT_CHANGED);
                        eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle);
                        mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                    }
                ); // end of mPasswordBox.TextInputStart

                /**
                 * @brief Sent from the Edit box when the return button was pressed.
                 * On iphone platform the virtual keyboard is not closed after receiving this event.
                 * EDIT_BOX_RETURN
                 */
                // Not available on Windows Phone 7.1
            }
 private void SetColors(SolidColorBrush foregroundColor, SolidColorBrush backgroundColor)
 {
     this.Background = backgroundColor;
     this.Foreground = foregroundColor;
 }
Beispiel #26
0
        /// <summary>
        /// Response for Branding Info
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pharmacyinfoforbrandingwebservicecall_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            GetPharmacyInformationResponse objPhBrandingInfoResponse = null;

            try
            {
                if (e.Result != null)
                {
                    var response = e.Result.ToString();
                    objPhBrandingInfoResponse = Utils.JsonHelper.Deserialize <GetPharmacyInformationResponse>(response);
                    if ((objPhBrandingInfoResponse.payload != null) && (objPhBrandingInfoResponse.status == 0))
                    {
                        App.ObjBrandingResponse = objPhBrandingInfoResponse;

                        App.BrandingHash = objPhBrandingInfoResponse.payload.branding_hash;
                        App.AdvtHash     = objPhBrandingInfoResponse.payload.advert_hash;
                        App.DrugsData    = objPhBrandingInfoResponse.payload.drugs_data;
                        App.DrugDBHash   = objPhBrandingInfoResponse.payload.drugs_hash;
                        App.AddImages    = null;
                        foreach (var item in objPhBrandingInfoResponse.payload.advert_data)
                        {
                            if (App.AddImages == null)
                            {
                                App.AddImages  = new List <BitmapImage>();
                                App.ImagesUrl  = new List <string>();
                                App.ImagesName = new List <string>();
                            }
                            if (item.image_url != null)
                            {
                                Uri         uri = new Uri(item.image_url.Replace("https", "http"));
                                BitmapImage bmi = new BitmapImage(uri);
                                App.ImagesUrl.Add(item.url);
                                App.ImagesName.Add(item.name);
                                App.AddImages.Add(bmi);
                            }
                            else
                            {
                                Color           backgroundColor = ConvertStringToColor(item.image_builder.background_color);
                                Color           foreroundColor2 = ConvertStringToColor(item.image_builder.font_color);
                                SolidColorBrush backgroundBrush = new SolidColorBrush(backgroundColor);
                                SolidColorBrush foregroundBrush = new SolidColorBrush(foreroundColor2);
                                string          text            = item.image_builder.line1 + Environment.NewLine + Environment.NewLine + item.image_builder.line2;
                                WriteableBitmap bmpSmall        = new WriteableBitmap(200, 120);

                                Grid grid = new Grid();
                                grid.Width  = bmpSmall.PixelWidth;
                                grid.Height = bmpSmall.PixelHeight;

                                var background = new Canvas();
                                background.Width      = bmpSmall.PixelWidth;
                                background.Height     = bmpSmall.PixelHeight;
                                background.Background = backgroundBrush;
                                var textBlock = new TextBlock();
                                textBlock.Width               = bmpSmall.PixelWidth;
                                textBlock.FontFamily          = new FontFamily("Segoe WP Light");
                                textBlock.Text                = text;
                                textBlock.HorizontalAlignment = HorizontalAlignment.Stretch;
                                textBlock.VerticalAlignment   = VerticalAlignment.Center;
                                textBlock.FontSize            = 12;
                                textBlock.TextWrapping        = TextWrapping.Wrap;
                                textBlock.Foreground          = foregroundBrush;
                                textBlock.TextAlignment       = TextAlignment.Center;
                                grid.Children.Add(background);
                                grid.Children.Add(textBlock);
                                grid.Measure(new Size(bmpSmall.PixelWidth, bmpSmall.PixelHeight));
                                grid.Arrange(new Rect(0, 0, bmpSmall.PixelWidth, bmpSmall.PixelHeight));
                                grid.UpdateLayout();
                                bmpSmall.Render(grid, null);
                                bmpSmall.Invalidate();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    bmpSmall.SaveJpeg(ms, 200, 120, 0, 100);
                                    BitmapImage bmp = new BitmapImage();
                                    bmp.SetSource(ms);
                                    App.ImagesUrl.Add(item.url);
                                    App.ImagesName.Add(item.name);
                                    App.AddImages.Add(bmp);
                                }
                            }
                        }
                    }
                    LoginUserDetailsWebService();
                }
            }
            catch (Exception ex)
            {
                objSignUpViewModel.ProgressBarVisibilty = Visibility.Collapsed;
                objSignUpViewModel.HitVisibility        = true;
                MessageBox.Show("Sorry, Unable to process your request.");
            }
        }
Beispiel #27
0
        private ImageSource PlatedImage(BitmapImage image)
        {
            if (!string.IsNullOrEmpty(BackgroundColor))
            {
                string currentBackgroundColor;
                if (BackgroundColor == "transparent")
                {
                    currentBackgroundColor = SystemParameters.WindowGlassBrush.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    currentBackgroundColor = BackgroundColor;
                }

                var padding = 8;
                var width   = image.Width + (2 * padding);
                var height  = image.Height + (2 * padding);
                var x       = 0;
                var y       = 0;

                var group     = new DrawingGroup();
                var converted = ColorConverter.ConvertFromString(currentBackgroundColor);
                if (converted != null)
                {
                    var color             = (Color)converted;
                    var brush             = new SolidColorBrush(color);
                    var pen               = new Pen(brush, 1);
                    var backgroundArea    = new Rect(0, 0, width, height);
                    var rectangleGeometry = new RectangleGeometry(backgroundArea);
                    var rectDrawing       = new GeometryDrawing(brush, pen, rectangleGeometry);
                    group.Children.Add(rectDrawing);

                    var imageArea    = new Rect(x + padding, y + padding, image.Width, image.Height);
                    var imageDrawing = new ImageDrawing(image, imageArea);
                    group.Children.Add(imageDrawing);

                    // http://stackoverflow.com/questions/6676072/get-system-drawing-bitmap-of-a-wpf-area-using-visualbrush
                    var visual  = new DrawingVisual();
                    var context = visual.RenderOpen();
                    context.DrawDrawing(group);
                    context.Close();

                    var bitmap = new RenderTargetBitmap(
                        Convert.ToInt32(width),
                        Convert.ToInt32(height),
                        _dpiScale100,
                        _dpiScale100,
                        PixelFormats.Pbgra32);

                    bitmap.Render(visual);

                    return(bitmap);
                }
                else
                {
                    ProgramLogger.Exception($"Unable to convert background string {BackgroundColor} to color for {Package.Location}", new InvalidOperationException(), GetType(), Package.Location);

                    return(new BitmapImage(new Uri(Constant.ErrorIcon)));
                }
            }
            else
            {
                // todo use windows theme as background
                return(image);
            }
        }
        /// <summary>
        /// Adds DocFX Note Support on top of Quote Formatting.
        /// </summary>
        /// <param name="element">QuoteBlock Element</param>
        /// <param name="context">Render Context</param>
        protected override void RenderQuote(QuoteBlock element, IRenderContext context)
        {
            // Grab the Local context and cast it.
            var localContext = context as UIElementCollectionRenderContext;
            var collection   = localContext?.BlockUIElementCollection;

            // Store these, they will be changed temporarily.
            var originalQuoteForeground = QuoteForeground;
            var originalLinkForeground  = LinkForeground;

            DocFXNote       noteType        = null;
            string          header          = null;
            SolidColorBrush localforeground = null;
            SolidColorBrush localbackground = null;
            string          symbolglyph     = string.Empty;

            // Check the required structure of the Quote is correct. Determine if it is a DocFX Note.
            if (element.Blocks.First() is ParagraphBlock para)
            {
                if (para.Inlines.First() is TextRunInline textinline)
                {
                    // Find the matching DocFX note style and header.
                    foreach (var style in styles)
                    {
                        // Search between stylisticly matching notes with different headers.
                        foreach (var identifier in style.Identifiers)
                        {
                            // Match the identifier with the start of the Quote to match.
                            if (textinline.Text.StartsWith(identifier.Key))
                            {
                                noteType    = style;
                                header      = identifier.Value;
                                symbolglyph = style.Glyph;

                                // Removes the identifier from the text
                                textinline.Text = textinline.Text.Replace(identifier.Key, string.Empty);

                                localforeground = style.LightForeground;
                                localbackground = style.LightBackground;
                            }
                        }
                    }

                    // Apply special formatting context.
                    if (noteType != null)
                    {
                        if (localContext?.Clone() is UIElementCollectionRenderContext newcontext)
                        {
                            localContext = newcontext;

                            localContext.TrimLeadingWhitespace = true;
                            QuoteForeground = Foreground;
                            LinkForeground  = localforeground;
                        }
                    }
                }
            }

            // Begins the standard rendering.
            base.RenderQuote(element, localContext);

            // Add styling to render if DocFX note.
            if (noteType != null)
            {
                // Restore original formatting properties.
                QuoteForeground = originalQuoteForeground;
                LinkForeground  = originalLinkForeground;

                if (localContext == null || collection?.Any() != true)
                {
                    return;
                }

                // Gets the current Quote Block UI from the UI Collection, and then styles it. Adds a header.
                if (collection.Last() is Border border)
                {
                    border.CornerRadius    = new CornerRadius(6);
                    border.BorderThickness = new Thickness(0);
                    border.Padding         = new Thickness(20);
                    border.Margin          = new Thickness(0, 5, 0, 5);
                    border.Background      = localbackground;

                    var headerPanel = new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        Margin      = new Thickness(0, 0, 0, 10)
                    };

                    headerPanel.Children.Add(new TextBlock
                    {
                        FontSize   = 18,
                        Foreground = localforeground,
                        Text       = symbolglyph,
                        FontFamily = new FontFamily("Segoe MDL2 Assets"),
                    });

                    headerPanel.Children.Add(new TextBlock
                    {
                        FontSize          = 16,
                        Foreground        = localforeground,
                        Margin            = new Thickness(5, 0, 0, 0),
                        Text              = header,
                        VerticalAlignment = VerticalAlignment.Center,
                        TextLineBounds    = TextLineBounds.Tight,
                        FontWeight        = FontWeights.SemiBold
                    });

                    if (border.Child is StackPanel panel)
                    {
                        panel.Children.Insert(0, headerPanel);
                    }
                }
            }
        }
Beispiel #29
0
 public MyModel()
 {
     ClickRed    = new ClickCommand(() => { Text = "青ボタンをクリック";  FillColor = new SolidColorBrush(Colors.Red); });
     ClickBlue   = new ClickCommand(() => { Text = "赤ボタンをクリック"; FillColor = new SolidColorBrush(Colors.Blue); });
     ClickYellow = new ClickCommand(() => { Text = "黄色ボタンをクリック"; FillColor = new SolidColorBrush(Colors.Yellow); });
 }
        /// <summary>
        /// Get the brush with <paramref name="color"/> color.
        /// </summary>
        /// <param name="color">The color.</param>
        /// <returns>Return the brush.</returns>
        private Brush GetBrush(OxyColor color)
        {
            if (!color.IsVisible())
            {
                return null;
            }

            Brush brush;
            if (!this.brushCache.TryGetValue(color, out brush))
            {
                brush = new SolidColorBrush(this.renderTarget, color.ToDXColor());
                this.brushCache.Add(color, brush);
            }

            return brush;
        }
Beispiel #31
0
        private static void Main()
        {
            matrix = new Matrix2D <Cell>(Program.MATRIX_SIZE_X, Program.MATRIX_SIZE_Y);
            Parallel.For(0, matrix.XSize, x =>
            {
                for (int y = 0; y < matrix.YSize; y++)
                {
                    matrix.SetNodeData(new Cell(false), x, y);
                }
            });


            var form = new RenderForm("Game Of Life");

            form.Size     = new System.Drawing.Size(MATRIX_SIZE_X, MATRIX_SIZE_Y);
            form.Icon     = null;
            form.KeyDown += Form_KeyDown;

            SharpDxHelper sharpDxHelper   = new SharpDxHelper();
            RenderTarget  d2dRenderTarget = sharpDxHelper.CreateRenderTarget(form);
            SwapChain     swapChain       = sharpDxHelper.swapChain;
            var           solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White);
            Stopwatch     stopwatch       = new Stopwatch();

            d2dRenderTarget.AntialiasMode = AntialiasMode.Aliased;

            var _memory        = new byte[MATRIX_SIZE_X * MATRIX_SIZE_Y * 4];
            var _backBufferBmp = new Bitmap(d2dRenderTarget, new Size2(MATRIX_SIZE_X, MATRIX_SIZE_Y), new BitmapProperties(d2dRenderTarget.PixelFormat));

            RenderLoop.Run(form, () =>
            {
                stopwatch.Restart();
                IterateEnergyCalculations();

                d2dRenderTarget.BeginDraw();

                stopwatch.Restart();
                Parallel.For(0, MATRIX_SIZE_X, x =>
                {
                    for (int y = 0; y < MATRIX_SIZE_Y; y++)
                    {
                        Color color    = matrix.GetNodeData(x, y).ConvertToColor32();
                        var i          = MATRIX_SIZE_X * 4 * y + x * 4;
                        _memory[i]     = color.B;
                        _memory[i + 1] = color.G;
                        _memory[i + 2] = color.R;
                        _memory[i + 3] = color.A;
                    }
                });

                _backBufferBmp.CopyFromMemory(_memory, MATRIX_SIZE_X * 4);
                d2dRenderTarget.DrawBitmap(_backBufferBmp, 1f, BitmapInterpolationMode.Linear);

                d2dRenderTarget.EndDraw();
                swapChain.Present(0, PresentFlags.None);

                FinalizeEnergyCalculations();

                long calculationTime = stopwatch.ElapsedMilliseconds;
                form.Text            = "Calculation Time: " + calculationTime.ToString() + "ms Live Cells: " + LivePixels.ToString();
            });


            sharpDxHelper.Destroy();
        }
Beispiel #32
0
            public override void SetupCustomUIElements(Controls.dynNodeView NodeUI)
            {
                //add a text box to the input grid of the control
                tb = new TextBox();
                tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                tb.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                NodeUI.inputGrid.Children.Add(tb);
                System.Windows.Controls.Grid.SetColumn(tb, 0);
                System.Windows.Controls.Grid.SetRow(tb, 0);

                //turn off the border
                SolidColorBrush backgroundBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0, 0, 0, 0));
                tb.Background = backgroundBrush;
                tb.BorderThickness = new Thickness(0);

                tb.DataContext = this;
                var bindingSymbol = new System.Windows.Data.Binding("Symbol")
                {
                    Mode = BindingMode.TwoWay
                };
                tb.SetBinding(TextBox.TextProperty, bindingSymbol);

                tb.TextChanged += new TextChangedEventHandler(tb_TextChanged);
            }
Beispiel #33
0
        /// <summary>
        /// The main update loop, happens every frame
        /// </summary>
        /// <param name="skeleton">the skeleton data of the player</param>
        private void Update(Skeleton skeleton)
        {
            CalculateDist(skeleton);

            UpdateGraphs();

            ChangeInstrument(skeleton);

            armLength = CalculateArmLength(skeleton);

            foreach (Peak p in leftArmPeaks)
            {
                p.TimeStep();
            }

            //check if right leg stomped
            if (LegStomp(false, skeleton))
            {
                if (isCalculatingBPM)
                {
                    bpmCalculatingLabel.Text = "BPM";

                    var greyBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6e6e6e"));
                    bpmCalculatingLabel.Foreground = greyBrush;
                    bpmCounterLabel.Foreground     = greyBrush;
                }
                else
                {
                    bpmCalculatingLabel.Text = "BPM (Calculating...)";

                    bpmCalculatingLabel.Foreground = new SolidColorBrush(Colors.Red);
                    bpmCounterLabel.Foreground     = new SolidColorBrush(Colors.Red);
                }
                isCalculatingBPM = !isCalculatingBPM;
                //Console.WriteLine("Right leg stomp");
            }
            //check if left leg stomped
            else if (LegStomp(true, skeleton))
            {
                //Console.WriteLine("Left leg stomp");
                //if currently recording and new record message comes in then wipe and start again
                if (isRecording)
                {
                    recordedNotes.RemoveAt(recordedNotes.Count - 1);
                }
                if (shouldRecord)
                {
                    shouldRecord        = false;
                    recordingLabel.Text = "Not Recording";
                    var greyBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6e6e6e"));
                    recordingLabel.Foreground   = greyBrush;
                    recordingCounter.Foreground = greyBrush;
                }
                else
                {
                    recordedNotes.Add(new Note[numberOfBeats]);
                    shouldRecord                = true;
                    isRecording                 = false;
                    recordingLabel.Text         = "Will Record";
                    recordingLabel.Foreground   = new SolidColorBrush(Colors.Orange);
                    recordingCounter.Foreground = new SolidColorBrush(Colors.Orange);
                }
            }

            if (isCalculatingBPM)
            {
                UpdatePeaks();
                CalculateBPM();
            }
            else
            {
                int noteValue = currentNoteValue;

                if (typeSlider.Value == 0)
                {
                    var wasArmMoved = WasArmMoved(skeleton);

                    if (wasArmMoved != ArmPos.Normal)
                    {
                        //Console.WriteLine("Arm moved!");
                        prevArmPos = ArmPos.Normal;

                        if (wasArmMoved == ArmPos.Raised)
                        {
                            currentNoteValue++;
                        }
                        else
                        {
                            currentNoteValue--;
                        }
                        currentNoteValue = Math.Max(24, Math.Min(currentNoteValue, 127));
                        noteValue        = currentNoteValue;

                        if (useScale)
                        {
                            var newNoteVal = Math.Floor(Convert.ToDouble(currentNoteValue) / currentScale.Length) * currentScale.Length;
                            //Console.WriteLine("New Note Val: " + newNoteVal);
                            var octave = newNoteVal / currentScale.Length;
                            //Console.WriteLine("Octave: " + octave);
                            var leftOver = currentNoteValue - newNoteVal;
                            //Console.WriteLine("Leftover: " + leftOver);
                            var tempNote = (int)(12 * octave + currentScale[(int)leftOver]);

                            //Console.WriteLine("Old note val: " + noteValue);
                            noteValue = Math.Max(24, tempNote);
                        }
                        //Console.WriteLine(currentNoteValue);
                        //Console.WriteLine("Note value: " + noteValue);
                    }
                }

                var shouldTick = bpm.ShouldTick();

                if (shouldTick > 0)
                {
                    //remove playing notes
                    while (playingNotes.Count > 0 && playingNotes.Min().GetTimeEnd() < currentTime)
                    {
                        Note endingNote = playingNotes.ExtractDominating().getNote();
                        endingNote = endingNote.EndNote();
                        EndNote(handle, endingNote);
                    }

                    int duration = 3;

                    var dist = skeleton.Joints[JointType.ShoulderLeft].Position.X - skeleton.Joints[JointType.WristLeft].Position.X;

                    //play a note
                    if (typeSlider.Value == 1)
                    {
                        double armHeight = CalculateJointHeight(skeleton.Joints[JointType.WristLeft], skeleton.Joints[JointType.ShoulderLeft], armLength);
                        duration = (int)((dist / Convert.ToDouble(armLength)) * 12);
                        if (useScale)
                        {
                            var newNoteVal = Math.Floor(armHeight / currentScale.Length) * currentScale.Length;
                            //Console.WriteLine("New Note Val: " + newNoteVal);
                            var octave = newNoteVal / currentScale.Length;
                            //Console.WriteLine("Octave: " + octave);
                            var leftOver = armHeight - newNoteVal;
                            //Console.WriteLine("Leftover: " + leftOver);
                            noteValue      = (int)(12 * octave + currentScale[(int)leftOver]);
                            noteLabel.Text = noteList[currentScale[(int)leftOver]];
                            //Console.WriteLine("Old note val: " + noteValue);
                            noteValue = Math.Max(0, noteValue);
                        }
                        else
                        {
                            noteValue = (int)armHeight;
                        }
                        noteValue += 24;
                        //Console.WriteLine("New Note: " + noteValue);
                    }
                    if (duration > 0)
                    {
                        Note thisNote = new Note(noteValue, currentInstrument, duration);
                        //Console.WriteLine("Playing note! " + currentTime + " Duration: "+duration);
                        PlayNote(handle, thisNote);
                        if (isRecording)
                        {
                            recordedNotes[recordedNotes.Count - 1][beatCounter] = thisNote;
                            //Console.WriteLine("Recording note at " + beatCounter + " " + recordedNotes[recordedNotes.Count - 1][beatCounter]);
                        }
                    }

                    var maxRecordings = recordedNotes.Count;

                    if (maxRecordings > 0)
                    {
                        if (isRecording)
                        {
                            maxRecordings--;
                        }
                        for (int i = 0; i < maxRecordings; i++)
                        {
                            if (recordedNotes[i][beatCounter] != null)
                            {
                                PlayNote(handle, recordedNotes[i][beatCounter]);
                                //Console.WriteLine("Playing recorded note at: " + beatCounter + " out of " + recordedNotes[i].Count());
                            }
                        }
                    }
                    currentTime++;

                    if (shouldTick == 1)
                    {
                        //play drum beat, needs to take what type
                        if (currentDrum.GetType() != typeof(Rest))
                        {
                            currentDrum.UpdateProbabilites(energy);
                            if (currentDrum.GetType() == typeof(HiHat))
                            {
                                PlayNote(handle, new Note(currentDrum.GetNote(), 99, 90));
                            }
                            else
                            {
                                PlayNote(handle, new Note(currentDrum.GetNote(), 99, 117));
                            }
                        }
                        currentDrum = currentDrum.GetNextNode();
                    }

                    // update recording.
                    // shouldTick == 2
                    else
                    {
                        if (currentTick > 1)
                        {
                            currentTick--;
                        }
                        else
                        {
                            currentTick = loopLength;
                            if (shouldRecord)
                            {
                                shouldRecord                = false;
                                isRecording                 = true;
                                recordingLabel.Text         = "Recording";
                                recordingLabel.Foreground   = new SolidColorBrush(Colors.Red);
                                recordingCounter.Foreground = new SolidColorBrush(Colors.Red);
                            }
                            else if (isRecording)
                            {
                                isRecording         = false;
                                recordingLabel.Text = "Not Recording";
                                var greyBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6e6e6e"));
                                recordingLabel.Foreground   = greyBrush;
                                recordingCounter.Foreground = greyBrush;
                            }
                        }
                        recordingCounter.Text = currentTick.ToString();
                    }

                    beatCounter++;
                    if (beatCounter >= numberOfBeats)
                    {
                        beatCounter = 0;
                    }
                    if (beatCounter % 2 == 0)
                    {
                        currentDrum = new Kick();
                        if (playKick)
                        {
                            PlayNote(handle, new Note(currentDrum.GetNote(), 99, 127));
                        }
                        else
                        {
                            PlayNote(handle, new Note(38, 99, 127));
                        }
                        playKick = !playKick;
                        energy   = GetEnergy();
                        currentDrum.UpdateProbabilites(energy);
                        currentDrum = currentDrum.GetNextNode();
                    }
                }
            }
        }
Beispiel #34
0
        void MainWindow_Load(object sender, EventArgs e)
        {
            DirectWriteFactory f = DirectWriteFactory.Create(DirectWriteFactoryType.Shared);
            _textFormat = f.CreateTextFormat("Verdana", null, FontWeight.Normal, FontStyle.Normal, FontStretch.Normal, 110, null);
            _textFormat.ParagraphAlignment = ParagraphAlignment.Far;
            _textFormat.TextAlignment = TextAlignment.Center;

            this.ClientSize = new System.Drawing.Size(600, 600);
            this._factory = Direct2DFactory.CreateFactory(FactoryType.SingleThreaded, DebugLevel.None);

            this._renderTarget = this._factory.CreateWindowRenderTarget(this, PresentOptions.None, RenderTargetProperties.Default);
            AntialiasMode amode = this._renderTarget.AntialiasMode;
            TextAntialiasMode tamode = this._renderTarget.TextAntialiasMode;
            this._strokeBrush = this._renderTarget.CreateSolidColorBrush(Color.FromARGB(Colors.Cyan, 1));
            this._strokeStyle = this._factory.CreateStrokeStyle(new StrokeStyleProperties(LineCapStyle.Flat,
                LineCapStyle.Flat, LineCapStyle.Round, LineJoin.Miter, 10, DashStyle.Dot, 0), null);

            this.Resize += new EventHandler(MainWindow_Resize);
        }
Beispiel #35
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var mod = value as ItemMod;

            if (mod == null)
            {
                return(null);
            }

            var inlines = new List <Inline>();

            var backrep = ItemAttributes.Attribute.Backreplace;

            var    matches = backrep.Matches(mod.Attribute).Cast <Match>().ToArray();
            int    from    = 0;
            string istring;
            Run    r;

            for (int i = 0; i < matches.Length && i < mod.Values.Count; i++)
            {
                var m = matches[i];
                istring = mod.Attribute.Substring(from, m.Index - from);
                var prefix = "";
                if (parameter != null && !string.IsNullOrEmpty(istring) && istring.Last() == '+')
                {
                    istring = istring.Substring(0, istring.Length - 1);
                    prefix  = "+";
                }
                r = new Run(istring);

                SolidColorBrush clr = GetColoringFor(mod, i);

                if ((istring == "-" || istring == "/" || istring == "+") && parameter != null)
                {
                    r.Foreground = clr;
                }

                if (parameter != null && !string.IsNullOrEmpty(istring) && istring[0] == '%')
                {
                    r.Foreground = GetColoringFor(mod, i - 1);
                }

                inlines.Add(r);

                r = new Run(prefix + mod.Values[i].ToString("###0.##"));
                if (parameter != null)
                {
                    r.Foreground = clr;
                }

                inlines.Add(r);

                from = m.Index + m.Length;
            }

            istring = mod.Attribute.Substring(from, mod.Attribute.Length - from);
            r       = new Run(istring);
            if (parameter != null && !string.IsNullOrEmpty(istring) && istring[0] == '%')
            {
                r.Foreground = GetColoringFor(mod, matches.Length - 1);
            }
            inlines.Add(r);


            return(inlines);
        }
Beispiel #36
0
        //        public EventHandler<AddressResult> addressChooserTask_Completed { get; set; }
        private void updateMyLocationPushPin(GeoCoordinate loc)
        {
            Grid ret = new Grid();

            ret.Height     = 29.284;
            ret.Width      = 29.284;
            ret.Visibility = System.Windows.Visibility.Visible;

            // Colors
            SolidColorBrush yellow = new SolidColorBrush();

            yellow.Color = Color.FromArgb(255, 255, 255, 0);
            SolidColorBrush black = new SolidColorBrush();

            black.Color = Color.FromArgb(255, 0, 0, 0);
            SolidColorBrush white = new SolidColorBrush();

            white.Color = Color.FromArgb(255, 255, 255, 255);

            // Rectangle
            Point rectPoint = new Point(0.5, 0.5);
            CompositeTransform rectRotate = new CompositeTransform();

            rectRotate.Rotation = 45;
            System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle();
            rect.Height                = 20;
            rect.Width                 = 20;
            rect.StrokeLineJoin        = PenLineJoin.Miter;
            rect.RenderTransformOrigin = rectPoint;
            rect.Fill              = black;
            rect.Stroke            = white;
            rect.UseLayoutRounding = true;
            rect.RenderTransform   = rectRotate;

            // Circle
            Ellipse circ = new Ellipse();

            circ.Width          = 10;
            circ.Height         = 10;
            circ.Stretch        = Stretch.Fill;
            circ.StrokeLineJoin = PenLineJoin.Miter;
            circ.Stroke         = yellow;
            circ.Fill           = yellow;

            // Add elements to the grid
            ret.Children.Add(rect);
            ret.Children.Add(circ);
            // Remove current location icon

            //current_position_layer.Children.Remove(curLoc);
            //curLoc = ret;

            //current_position_layer.AddChild(ret, loc);
            if (Map.Children.Contains(ret) != true)
            {
                Map.Children.Add(ret);
            }
            else
            {
                Map.Children.Remove(ret);
                Map.Children.Add(ret);
            }
        }
Beispiel #37
0
        private void TextByGlyph(RectangleF rect, string text, TextInfo info, SolidColorBrush brush)
        {
            FontFace fontFace;

            if (!m_faceMap.TryGetValue(info.Font, out fontFace))
            {
                using (var f = new SharpDX.DirectWrite.Factory())
                    using (var collection = f.GetSystemFontCollection(false))
                    {
                        int familyIndex;
                        if (!collection.FindFamilyName(info.Font.FamilylName, out familyIndex))
                        {
                            return;
                        }

                        using (var family = collection.GetFontFamily(familyIndex))
                            using (var font = family.GetFont(0))
                            {
                                fontFace = new FontFace(font);
                                m_faceMap.Add(info.Font, fontFace);
                            }
                    }
            }

            var codePoints = EnumCodePoints(text).ToArray();
            var indices    = fontFace.GetGlyphIndices(codePoints);

            // Get glyph
            var metrices = fontFace.GetDesignGlyphMetrics(indices, false);

            // draw
            var glyphRun = new GlyphRun
            {
                FontFace = fontFace,
                Indices  = indices,
                FontSize = info.Font.Size,
            };

            bool done = false;

            using (var f = new SharpDX.DirectWrite.Factory())
                using (var ff = f.QueryInterface <SharpDX.DirectWrite.Factory4>())
                {
                    var desc = new GlyphRunDescription
                    {
                    };
                    ColorGlyphRunEnumerator it;
                    var result = ff.TryTranslateColorGlyphRun(0, 0, glyphRun,
                                                              null, MeasuringMode.Natural, null, 0, out it);
                    if (result.Code == DWRITE_E_NOCOLORLOR)
                    {
                        m_device.D2DDeviceContext.DrawGlyphRun(rect.TopLeft + new Vector2(0, info.Font.Size), glyphRun, brush, MeasuringMode.Natural);
                    }
                    else
                    {
                        while (true)
                        {
                            var colorBrush = GetOrCreateBrush(new Color4(
                                                                  it.CurrentRun.RunColor.R,
                                                                  it.CurrentRun.RunColor.G,
                                                                  it.CurrentRun.RunColor.B,
                                                                  it.CurrentRun.RunColor.A));
                            m_device.D2DDeviceContext.DrawGlyphRun(rect.TopLeft + new Vector2(0, info.Font.Size),
                                                                   it.CurrentRun.GlyphRun, colorBrush, MeasuringMode.Natural);
                            done = true;

                            SharpDX.Mathematics.Interop.RawBool hasNext;
                            it.MoveNext(out hasNext);
                            if (!hasNext)
                            {
                                break;;
                            }
                        }
                    }
                }
        }
Beispiel #38
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            // how much space we got for cells
            var maxWidth  = ((int)viewport.Width / CellWidth) + 1;
            var maxHeight = ((int)viewport.Height / CellHeight) + 1;

            // how many cells we will draw
            var cellsHorizontally = maxWidth > matrixWidth ? matrixWidth : maxWidth;
            var cellsVertically   = maxHeight > matrixHeight ? matrixHeight : maxHeight;

            // number of cell which will be drawn
            var scaledOffsetX = (int)offset.X / CellWidth;
            var scaledOffsetY = (int)offset.Y / CellHeight;

            // sets how much of cell on border should be drawn
            var offsetDiffX = offset.X - scaledOffsetX * CellWidth;
            var offsetDiffY = offset.Y - scaledOffsetY * CellHeight;

            // background
            var background      = new Rect(0, 0, cellsHorizontally * CellWidth, cellsVertically * CellHeight);
            var backgroundColor = new SolidColorBrush(Colors.Yellow);

            drawingContext.DrawRectangle(backgroundColor, null, background);

            // hovering
            if (currentCell.X >= 0 || currentCell.Y >= 0)
            {
                // hover x line
                var rect = new Rect(0,
                                    (currentCell.Y - scaledOffsetY) * CellHeight - offsetDiffY,
                                    CellWidth * cellsVertically,
                                    CellHeight);

                var brush = new SolidColorBrush(Colors.GreenYellow);
                drawingContext.DrawRectangle(brush, null, rect);

                // hover y line
                rect = new Rect((currentCell.X - scaledOffsetX) * CellWidth - offsetDiffX,
                                0,
                                CellWidth,
                                CellHeight * cellsHorizontally);

                brush = new SolidColorBrush(Colors.GreenYellow);
                drawingContext.DrawRectangle(brush, null, rect);

                // hover cell
                rect = new Rect(
                    (currentCell.X - scaledOffsetX) * CellWidth - offsetDiffX,
                    (currentCell.Y - scaledOffsetY) * CellHeight - offsetDiffY,
                    CellWidth,
                    CellHeight);

                brush = new SolidColorBrush(Colors.Red);
                drawingContext.DrawRectangle(brush, null, rect);
            }

            // grid
            var pen = new Pen(Brushes.Black, 1);

            // grid x
            for (int i = 0; i <= cellsHorizontally; i++)
            {
                drawingContext.DrawLine(pen,
                                        new Point(i * CellWidth - offsetDiffX, 0),
                                        new Point(i * CellWidth - offsetDiffX,
                                                  cellsVertically * CellWidth));
            }
            // grid y
            for (int i = 0; i <= cellsVertically; i++)
            {
                drawingContext.DrawLine(pen,
                                        new Point(0, i * CellHeight - offsetDiffY),
                                        new Point(cellsHorizontally * CellHeight,
                                                  i * CellHeight - offsetDiffY));
            }

            // sometimes happens when half of cell is hidden in scroll so text isnt drawn
            // so lets drawn one more cell
            cellsHorizontally = maxWidth > matrixWidth ? matrixWidth : maxWidth + 1;
            cellsVertically   = maxHeight > matrixHeight ? matrixHeight : maxHeight + 1;

            // text
            for (int i = 0; i < cellsHorizontally; i++)
            {
                for (int j = 0; j < cellsVertically; j++)
                {
                    drawingContext.DrawImage(
                        CreateText((i + scaledOffsetX) * (j + scaledOffsetY)),
                        new Rect(i * CellWidth - offsetDiffX, j * CellHeight - offsetDiffY, CellWidth, CellHeight));
                }
            }
        }
        private FrameworkElement GetCourseElement(Course course, int time, int day = -1)
        {
            var textBlock = new TextBlock();

            textBlock.Text = course.Name;
            //for (int i = 0, count = course.ClassRooms.Count; i < count; i++)
            //textBlock.Text += (i == 0 ? "\n" : "") + course.ClassRooms[i] + (i < count - 1 ? "、" : "");

            textBlock.TextAlignment     = TextAlignment.Center;
            textBlock.TextWrapping      = TextWrapping.Wrap;
            textBlock.FontSize          = 16;
            textBlock.VerticalAlignment = VerticalAlignment.Center;

            Border border = new Border();

            border.MinHeight = 50;
            border.Child     = textBlock;
            border.Tapped   += async(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) =>
            {
                string content = "";

                if (course.ClassRooms.Count > 0)
                {
                    foreach (string classRoom in course.ClassRooms)
                    {
                        content += classRoom + " ";
                    }
                    content += "\n";
                }

                string timeString = Course.GetTimeString(time);

                if (timeString != null)
                {
                    content += timeString + "\n";
                }

                content += string.Format("學分: {0} 時數: {1}\n", course.Credit, course.Hours);

                if (course.Teachers.Count > 0)
                {
                    foreach (string teacher in course.Teachers)
                    {
                        content += teacher + " ";
                    }
                    content += "\n";
                }

                if (!string.IsNullOrWhiteSpace(course.Note))
                {
                    content += course.Note;
                }

                var dialog = new MessageDialog(content, course.Name);
                if (!(string.IsNullOrWhiteSpace(course.IdForSelect) || course.IdForSelect == "0"))
                {
                    dialog.Commands.Add(new UICommand("詳細資料", (command) =>
                    {
                        Frame.Navigate(typeof(CourseDetailPage), course.IdForSelect);
                    }));
                }
                dialog.Commands.Add(new UICommand("關閉"));

                //Send GA Event
                App.Current.GATracker.SendEvent("Other", "Tap on Course", null, 0);

                await dialog.ShowAsync();
            };

            Brush backColor, hoverColor;

            if (DateTime.Today.DayOfWeek == (DayOfWeek)(day + 1 % 7))
            {
                backColor  = new SolidColorBrush(Color.FromArgb(255, 209, 52, 56));
                hoverColor = new SolidColorBrush(Color.FromArgb(255, 180, 52, 56));
            }
            else
            {
                backColor  = new SolidColorBrush(Color.FromArgb(128, 128, 128, 128));
                hoverColor = new SolidColorBrush(Color.FromArgb(255, 128, 128, 128));
            }

            border.Background = backColor;
            border.Padding    = new Thickness(5);
            border.Margin     = new Thickness(1);

            border.PointerEntered += (sender, e) =>
            {
                border.Background = hoverColor;
            };

            border.PointerExited += (sender, e) =>
            {
                border.Background = backColor;
            };

            return(border);
        }
        public void Should_Not_Alter_Lines_After_TextStyleSpan_Was_Applied()
        {
            using (Start())
            {
                const string text = "אחד !\ntwo !\nשְׁלוֹשָׁה !";

                var red   = new SolidColorBrush(Colors.Red).ToImmutable();
                var black = Brushes.Black.ToImmutable();

                var expected = new TextLayout(
                    text,
                    Typeface.Default,
                    12.0f,
                    black,
                    textWrapping: TextWrapping.Wrap);

                var expectedGlyphs = expected.TextLines.Select(x => string.Join('|', x.TextRuns.Cast <ShapedTextCharacters>().SelectMany(x => x.ShapedBuffer.GlyphIndices))).ToList();

                var outer = new GraphemeEnumerator(text.AsMemory());
                var inner = new GraphemeEnumerator(text.AsMemory());
                var i     = 0;
                var j     = 0;

                while (true)
                {
                    while (inner.MoveNext())
                    {
                        j += inner.Current.Text.Length;

                        if (j + i > text.Length)
                        {
                            break;
                        }

                        var spans = new[]
                        {
                            new ValueSpan <TextRunProperties>(i, j,
                                                              new GenericTextRunProperties(Typeface.Default, 12, foregroundBrush: red))
                        };

                        var actual = new TextLayout(
                            text,
                            Typeface.Default,
                            12.0f,
                            black,
                            textWrapping: TextWrapping.Wrap,
                            textStyleOverrides: spans);

                        var actualGlyphs = actual.TextLines.Select(x => string.Join('|', x.TextRuns.Cast <ShapedTextCharacters>().SelectMany(x => x.ShapedBuffer.GlyphIndices))).ToList();

                        Assert.Equal(expectedGlyphs.Count, actualGlyphs.Count);

                        for (var k = 0; k < expectedGlyphs.Count; k++)
                        {
                            Assert.Equal(expectedGlyphs[k], actualGlyphs[k]);
                        }
                    }

                    if (!outer.MoveNext())
                    {
                        break;
                    }

                    inner = new GraphemeEnumerator(text.AsMemory());

                    i += outer.Current.Text.Length;
                }
            }
        }
Beispiel #41
0
        private static bool LoadChartSettings()
        {
            SeriesConfigurations = new List <SeriesConfig>();
            try
            {
                var chartSettingsPath = ConfigurationManager.AppSettings["chartSettingsPath"];
                chartSettingsPath = string.IsNullOrEmpty(chartSettingsPath) ? @".\" : chartSettingsPath;

                var chartSettings = File.ReadAllText(chartSettingsPath + "ChartSettings.json");
                var settingsJObj  = JObject.Parse(chartSettings);

                UserName = (string)settingsJObj["userName"];
                Password = (string)settingsJObj["password"];

                ChartTitle      = (string)settingsJObj["chart"]["title"];
                TimezoneOffset  = int.TryParse((string)settingsJObj["chart"]["timezoneOffset"], out int tzOffset) ? tzOffset : 0;
                ChartTimeFormat = (string)settingsJObj["chart"]["timeFormat"] ?? "HH:mm:ss";
                SampleCount     = int.TryParse((string)settingsJObj["chart"]["sampleCount"], out int sampleCount) ? sampleCount : SampleCount;

                DeviceId              = (string)settingsJObj["stream"]["deviceId"];
                Filter                = (string)settingsJObj["stream"]["filter"];
                PrefetchMinutes       = int.TryParse((string)settingsJObj["stream"]["samplePrefetchMinutes"], out int prefetchMin) ? prefetchMin : PrefetchMinutes;
                SampleIntervalSeconds = int.TryParse((string)settingsJObj["stream"]["sampleIntervalSeconds"], out int intervalSec) ? intervalSec : SampleIntervalSeconds;

                var seriesConfig = (JArray)settingsJObj["seriesConfig"];
                foreach (var series in seriesConfig)
                {
                    if (ValidatePath((string)series["path"]))
                    {
                        Brush strokeColor;
                        try
                        {
                            strokeColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString((string)series["color"]));
                        }
                        catch (Exception)
                        {
                            strokeColor = null;
                        }
                        var config = new SeriesConfig()
                        {
                            Name           = (string)series["name"],
                            Units          = (string)(series["units"] ?? ""),
                            Path           = (string)series["path"],
                            StrokeColor    = strokeColor,
                            LineSmoothness = (double)(series["lineSmoothness"] ?? defaultLineSmoothness)
                        };
                        config.Name = (string.IsNullOrEmpty(config.Name)) ? config.Path.Split('.').Last() : config.Name;
                        SeriesConfigurations.Add(config);

                        if (series["min"] != null)
                        {
                            LimitsMinPath = (string)series["path"];
                        }
                        if (series["max"] != null)
                        {
                            LimitsMaxPath = (string)series["path"];
                        }
                    }
                    else
                    {
                        var dialogBoxResult = MessageBox.Show(
                            string.Format("Data series path: {0} is empty or invalid. No data for this series will be processed", (string)series["path"]),
                            "CloudChart: ChartSettings.json Invalid",
                            MessageBoxButton.OK,
                            MessageBoxImage.Asterisk
                            );
                    }
                }

                ChartDurationSeconds = (SampleCount * SampleIntervalSeconds);

                return(true);
            }
            catch (Exception)           // just suck up any exceptions, app init will detect problems in chart settings
            {
                return(false);
            }
        }
Beispiel #42
0
        public Ellipse theBody()
        {
            playerCanv.Children.Remove(refreshedbody);

            Ellipse            body           = new Ellipse();
            TransformGroup     bodyTransGroup = new TransformGroup();
            TranslateTransform bodyTranslate  = new TranslateTransform();
            Point bodyLocation = new Point();

            body.Width  = 50;
            body.Height = 50;
            SolidColorBrush sb = new SolidColorBrush(Colors.Black);

            body.Fill = sb;

            bodyTranslate.X = X + bodyTranslate.X + velocityMovementx;
            bodyTranslate.Y = Y + bodyTranslate.Y + velocityMovementy;


            //Sets the body to stay inside the boundaries
            bodyLocation.X = bodyLocation.X + bodyTranslate.X;
            bodyLocation.Y = bodyLocation.Y + bodyTranslate.Y;

            Point aTempPoint = new Point();

            aTempPoint = bodyLocation;
            int lastPointIndex = 0;

            savebODYLocation(aTempPoint);


            //Saves the locations of the player
            if (bodyLocation.X <= 1)
            {
                lastPointIndex      = locBodySaved.LastIndexOf(aTempPoint);
                checkBodyBoundaries = true;


                bodyTranslate.X = 1;
                bodyLocation.X  = 1;
            }
            else if ((bodyLocation.X >= playerCanv.ActualWidth - 50) && playerCanv.ActualWidth - 50 > 0)
            {
                lastPointIndex      = locBodySaved.LastIndexOf(aTempPoint);
                checkBodyBoundaries = true;
                bodyTranslate.X     = playerCanv.ActualWidth - 50;
                bodyLocation.X      = playerCanv.ActualWidth - 50;
            }

            if (bodyLocation.Y <= 1)
            {
                lastPointIndex      = locBodySaved.LastIndexOf(aTempPoint);
                checkBodyBoundaries = true;
                bodyTranslate.Y     = 1 /*locBodySaved[locBodySaved.Count-3].X*/;
                bodyLocation.Y      = 1;
                //bodyTranslate.Y = locBodySaved[lastPointIndex - 1].Y;
                //bodyLocation.Y = locBodySaved[lastPointIndex - 1].Y;
            }
            else if ((bodyLocation.Y >= playerCanv.ActualHeight - 50) && playerCanv.ActualHeight - 50 > 0)
            {
                savebODYLocation(aTempPoint);
                checkBodyBoundaries = true;
                bodyTranslate.Y     = playerCanv.ActualHeight - 50 /*locBodySaved[locBodySaved.Count-3].X*/;
                bodyLocation.Y      = playerCanv.ActualHeight - 50;
                //bodyTranslate.Y = locBodySaved[lastPointIndex - 1].Y;
                //bodyLocation.Y = locBodySaved[lastPointIndex - 1].Y;
            }



            bodyTransGroup.Children.Add(bodyTranslate);
            body.RenderTransform = bodyTransGroup;


            //player Redrawn
            playerCanv.Children.Add(body);
            return(body);
        }
Beispiel #43
0
 public void StrokeColor(Color color)
 {
     LineColor = new SolidColorBrush(color);
 }
        protected override void OnCreateDeviceResources(WindowRenderTarget renderTarget)
        {
            base.OnCreateDeviceResources(renderTarget);

            this._blackBrush = renderTarget.CreateSolidColorBrush(Color.FromARGB(Colors.Black, 1));
            this._customRenderer = new CustomTextRendererWithEffects(this.Direct2DFactory, renderTarget, this._blackBrush);
        }
        void BuildPrimaryPlane(InspectTreeState state)
        {
            var   displayMode = state.Mode;
            Brush brush       = new SolidColorBrush(EmptyColor);
            var   view        = Node.View;
            var   parent      = Node.View.Parent;
            var   matrix      = Matrix3D.Identity;

            if (view.Layer != null)
            {
                view = view.Layer;
            }

            var zFightOffset = childIndex * zFightIncrement;
            var zOffset      = ZSpacing + zFightOffset;

            if (view.Transform != null)
            {
                var render = view.Transform;
                matrix = new Matrix3D {
                    M11     = render.M11,
                    M12     = render.M12,
                    M13     = render.M13,
                    M14     = render.M14,
                    M21     = render.M21,
                    M22     = render.M22,
                    M23     = render.M23,
                    M24     = render.M24,
                    M31     = render.M31,
                    M32     = render.M32,
                    M33     = render.M33,
                    M34     = render.M34,
                    OffsetX = render.OffsetX,
                    OffsetY = render.OffsetY,
                    OffsetZ = render.OffsetZ + zOffset
                };
            }

            var size   = new Size(view.Width, view.Height);
            var visual = new DrawingVisual();

            using (var context = visual.RenderOpen()) {
                if (view.BestCapturedImage != null && displayMode.HasFlag(DisplayMode.Content))
                {
                    var bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = new MemoryStream(view.BestCapturedImage);
                    bitmap.EndInit();

                    context.DrawImage(bitmap, new Rect(size));
                }

                if (displayMode.HasFlag(DisplayMode.Frames))
                {
                    context.DrawRectangle(
                        null,
                        new Pen(new SolidColorBrush(Color.FromRgb(0xd3, 0xd3, 0xd3)), 0.5),
                        new Rect(size));
                }
            }

            brush = new ImageBrush {
                ImageSource = new DrawingImage(visual.Drawing)
            };

            var geometry = new MeshGeometry3D()
            {
                Positions = new Point3DCollection {
                    new Point3D(0, 0, 0),
                    new Point3D(0, -size.Height, 0),
                    new Point3D(size.Width, -size.Height, 0),
                    new Point3D(size.Width, 0, 0)
                },
                TextureCoordinates = new PointCollection {
                    new Point(0, 0),
                    new Point(0, 1),
                    new Point(1, 1),
                    new Point(1, 0)
                },
                TriangleIndices = new Int32Collection {
                    0, 1, 2, 0, 2, 3
                },
            };

            var backGeometry = new MeshGeometry3D()
            {
                Positions          = geometry.Positions,
                TextureCoordinates = geometry.TextureCoordinates,
                TriangleIndices    = geometry.TriangleIndices,
                Normals            = new Vector3DCollection {
                    new Vector3D(0, 0, -1),
                    new Vector3D(0, 0, -1),
                    new Vector3D(0, 0, -1),
                    new Vector3D(0, 0, -1)
                }
            };

            material = new DiffuseMaterial(brush)
            {
                Color = BlurColor
            };

            Content = new Model3DGroup()
            {
                Children = new Model3DCollection {
                    new GeometryModel3D {
                        Geometry = geometry,
                        Material = material
                    },
                    new GeometryModel3D {
                        Geometry     = backGeometry,
                        BackMaterial = material,
                    },
                },
                Transform = new ScaleTransform3D {
                    ScaleX = Math.Ceiling(view.Width) / size.Width,
                    ScaleY = -Math.Ceiling(view.Height) / size.Height,
                    ScaleZ = 1
                }
            };

            var group = new Transform3DGroup();

            if ((parent == null && !Node.View.IsFakeRoot) || (parent?.IsFakeRoot ?? false))
            {
                var unitScale = 1.0 / Math.Max(view.Width, view.Height);
                group.Children = new Transform3DCollection {
                    new TranslateTransform3D {
                        OffsetX = -view.Width / 2.0,
                        OffsetY = -view.Height / 2.0,
                        OffsetZ = zOffset
                    },
                    new ScaleTransform3D(unitScale, -unitScale, 1),
                    expandTransform
                };
            }
            else
            {
                if (view.Transform != null)
                {
                    group.Children = new Transform3DCollection {
                        new MatrixTransform3D()
                        {
                            Matrix = matrix
                        },
                        expandTransform
                    };
                }
                else
                {
                    group.Children = new Transform3DCollection {
                        new TranslateTransform3D(view.X, view.Y, zOffset),
                        expandTransform
                    };
                }
            }
            Transform = group;
        }
Beispiel #46
0
            public dynSymbol()
            {
                //add a text box to the input grid of the control
                tb = new TextBox();
                tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                tb.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                NodeUI.inputGrid.Children.Add(tb);
                System.Windows.Controls.Grid.SetColumn(tb, 0);
                System.Windows.Controls.Grid.SetRow(tb, 0);
                tb.Text = "";
                //tb.KeyDown += new System.Windows.Input.KeyEventHandler(tb_KeyDown);
                //tb.LostFocus += new System.Windows.RoutedEventHandler(tb_LostFocus);

                //turn off the border
                SolidColorBrush backgroundBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0, 0, 0, 0));
                tb.Background = backgroundBrush;
                tb.BorderThickness = new Thickness(0);

                OutPortData.Add(new PortData("", "Symbol", typeof(object)));

                NodeUI.RegisterAllPorts();
            }
Beispiel #47
0
        public void ColorFigures()
        {
            var brightness = 1.0;
            var delta      = brightness / numberOfLevels;

            MakeFiguresBlack(Net.Nodes, Net.arcs);
            foreach (var figure in Net.Nodes)
            {
                (GetKeyByValueForFigures(figure) as Shape).Fill.Opacity = 1.0;
                var brush = new SolidColorBrush {
                    Color = Colors.White
                };
                (GetKeyByValueForFigures(figure) as Shape).Fill = brush;
            }

            var counter  = 0;
            var quantity = 0;
            var reset    = true;

            for (var i = colored.Count - 1; i >= 0; i--)
            {
                var temp  = GetKeyByValueForFigures(colored[i]) as Shape;
                var brush = new SolidColorBrush(Colors.Blue)
                {
                    Opacity = brightness
                };
                counter++;
                temp.Fill = brush;

                if (reset)
                {
                    if (colored[i] is VPlace)
                    {
                        var arcs = GetIngoingArcs(colored[i]);
                        if (arcs.Count != 0)
                        {
                            quantity = GetOutgoingArcs(arcs[0].From).Count;
                        }
                        else
                        {
                            var j = i + 1;
                            if (j < colored.Count)
                            {
                                while ((colored[j] is VPlace))
                                {
                                    j++;
                                }
                                quantity = GetIngoingArcs(colored[j]).Count;
                            }
                            else
                            {
                                quantity = 1;
                            }
                        }
                    }
                    else
                    {
                        quantity = 1;
                    }
                    reset = false;
                }

                if (counter != quantity)
                {
                    continue;
                }

                counter     = 0;
                brightness -= delta;
                reset       = true;
            }
        }
Beispiel #48
0
        /// <summary>
        /// This method creates the render target and all associated D2D and DWrite resources
        /// </summary>
        void CreateDeviceResources()
        {
            // Only calls if resources have not been initialize before
            if (renderTarget == null)
            {
                // Create the render target
                SizeU size = new SizeU((uint)host.ActualWidth, (uint)host.ActualHeight);
                RenderTargetProperties props = new RenderTargetProperties();
                HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties(host.Handle, size, PresentOptions.None);
                renderTarget = d2dFactory.CreateHwndRenderTarget(props, hwndProps);

                // Create the black brush for text
                blackBrush = renderTarget.CreateSolidColorBrush(new ColorF(0 ,0, 0, 1));

                inlineImage = new ImageInlineObject(renderTarget, wicFactory, "TextInlineImage.img1.jpg");

                TextRange textRange = new TextRange(14, 1);
                textLayout.SetInlineObject(inlineImage, textRange);
            }
        }
Beispiel #49
0
        public bool SimulateOneStep()
        {
            isSomethingChanged = true;

            if (isItFirstStep)
            {
                weights.Clear();

                foreach (var place in Net.places)
                {
                    weights.Add(place.Id, place.NumberOfTokens);
                }
                isItFirstStep = false;
            }

            List <VPlace> initialPlaces = new List <VPlace>();

            foreach (VPlace place in Net.places)
            {
                int numberOfOutgoingArcs = place.ThisArcs.Count(t => place != t.To);

                //todo вот здесь если токены не кружками, то будет плохо
                if (place.TokensList.Count != 0 && numberOfOutgoingArcs != 0)
                {
                    initialPlaces.Add(place);
                }
                foreach (Ellipse ellipse in place.TokensList)
                {
                    ellipse.Fill = Brushes.Black;
                }
            }

            var outgoingTransitions = new List <VTransition>();

            foreach (var place in initialPlaces)
            {
                foreach (var arc1 in place.ThisArcs)
                {
                    if (arc1.From != place)
                    {
                        continue;
                    }

                    foreach (var arc2 in arc1.To.ThisArcs)
                    {
                        var mayBeEnabled = true;

                        if (arc2.To != arc1.To)
                        {
                            continue;
                        }

                        foreach (var arc in arc1.To.ThisArcs)
                        {
                            if (arc.To != arc1.To)
                            {
                                continue;
                            }
                            int numberOfRequiredTokens;
                            int.TryParse(arc.Weight, out numberOfRequiredTokens);
                            var numberOfExistingTokens = (arc.From as VPlace).NumberOfTokens;

                            if (numberOfRequiredTokens <= numberOfExistingTokens)
                            {
                                continue;
                            }
                            mayBeEnabled = false;
                            break;
                        }
                        if (!outgoingTransitions.Contains(arc1.To as VTransition) && mayBeEnabled)
                        {
                            outgoingTransitions.Add(arc1.To as VTransition);
                        }
                    }
                }
            }

            if (outgoingTransitions.Count != 0)
            {
                foreach (VTransition transition in outgoingTransitions)
                {
                    (GetKeyByValueForFigures(transition)
                     as Shape).Stroke = Brushes.Black;
                }


                if (_isTransitionSelected == false)
                {
                    if (_modeChoice == Choice.Forced)
                    {
                        if (outgoingTransitions.Count > 1)
                        {
                            _leftMouseButtonMode = LeftMouseButtonMode.ChooseTransition;
                            foreach (VTransition transition in outgoingTransitions)
                            {
                                SolidColorBrush brush = new SolidColorBrush();
                                brush.Color = Color.FromRgb(255, 0, 51);
                                (GetKeyByValueForFigures(transition) as Shape).Stroke = brush;
                            }
                            return(false);
                        }
                        else
                        {
                            enabledTransition = outgoingTransitions[0];
                        }
                    }
                    else
                    {
                        var transitionsWithTopPriority = new List <VTransition>();
                        outgoingTransitions.Sort(new Comparison <VTransition>((VTransition a, VTransition b) => (a.Priority - b.Priority)));

                        var transitionWithTopPriority = outgoingTransitions.Find(new Predicate <VTransition>((VTransition t) => t.Priority > 0));

                        int topPriority = 0;
                        if (transitionWithTopPriority != null)
                        {
                            topPriority = transitionWithTopPriority.Priority;
                        }

                        outgoingTransitions = outgoingTransitions.FindAll(new Predicate <VTransition>((VTransition a) => (a.Priority == topPriority || a.Priority == 0)));

                        int indexOfEnabledTransition = MainRandom.Next(0, outgoingTransitions.Count);
                        enabledTransition = outgoingTransitions[indexOfEnabledTransition];
                    }
                }
                _isTransitionSelected = false;
                _leftMouseButtonMode  = LeftMouseButtonMode.Select;

                var isFirstRemove = true;

                foreach (var arc in enabledTransition.ThisArcs)
                {
                    if (arc.From == enabledTransition)
                    {
                        continue;
                    }

                    if (colored.Contains(arc.From))
                    {
                        colored.Remove(arc.From);
                        if (isFirstRemove)
                        {
                            numberOfLevels--;
                        }
                        isFirstRemove = false;
                    }
                    colored.Add(arc.From);
                }
                numberOfLevels++;

                if (colored.Contains(enabledTransition))
                {
                    colored.Remove(enabledTransition);
                    numberOfLevels--;
                }
                colored.Add(enabledTransition);

                numberOfLevels++;
                isFirstRemove = true;
                foreach (VArc arc in enabledTransition.ThisArcs)
                {
                    VPlace changedPlace;
                    if (arc.From != enabledTransition)
                    {
                        changedPlace = (arc.From as VPlace);
                        if (changedPlace.NumberOfTokens != 0)
                        {
                            if (changedPlace.NumberOfTokens < 5)
                            {
                                RemoveTokens(changedPlace);
                            }
                            else
                            {
                                MainModelCanvas.Children.Remove(changedPlace.NumberOfTokensLabel);
                            }
                        }
                        int delta;
                        int.TryParse(arc.Weight, out delta);
                        changedPlace.NumberOfTokens -= delta;
                    }
                    else
                    {
                        changedPlace = (arc.To as VPlace);
                        if (changedPlace.NumberOfTokens != 0)
                        {
                            if (changedPlace.NumberOfTokens < 5)
                            {
                                RemoveTokens(changedPlace);
                            }
                            else
                            {
                                MainModelCanvas.Children.Remove(changedPlace.NumberOfTokensLabel);
                            }
                        }
                        int delta;
                        int.TryParse(arc.Weight, out delta);
                        changedPlace.NumberOfTokens += delta;
                        if (colored.Contains(changedPlace))
                        {
                            colored.Remove(changedPlace);
                            if (isFirstRemove)
                            {
                                numberOfLevels--;
                            }
                            isFirstRemove = false;
                        }
                        colored.Add(changedPlace);
                    }



                    AddTokens(changedPlace);
                    if (arc.From != enabledTransition)
                    {
                        continue;
                    }
                    var placeToColor = (arc.To as VPlace);
                    foreach (var ellepse in placeToColor.TokensList)
                    {
                        var brush = new SolidColorBrush {
                            Color = Color.FromRgb(153, 255, 102)
                        };
                        ellepse.Fill   = brush;
                        ellepse.Stroke = Brushes.Black;
                    }
                }
                numberOfLevels++;

                if (simulationMode == SimulationMode.wave)
                {
                    ColorFigures();
                }


                if (marking.Count <= 0)
                {
                    return(false);
                }
                oneStepMarking = new int[Net.places.Count];
                for (int j = 0; j < Net.places.Count; j++)
                {
                    oneStepMarking[j] = Net.places[j].NumberOfTokens;
                }

                marking.Push(oneStepMarking);
                maxMarking++;

                textBoxSimulationCurrentMarking.Text += "M_" + (maxMarking - 1) + " = { ";
                for (int j = 0; j < oneStepMarking.Length - 1; j++)
                {
                    textBoxSimulationCurrentMarking.Text += oneStepMarking[j] + " | ";
                }
                textBoxSimulationCurrentMarking.Text += oneStepMarking[oneStepMarking.Length - 1] + " }\n";
                textBoxSimulationCurrentMarking.ScrollToEnd();
                return(false);
            }
            else
            {
                return(true);
            }
        }
Beispiel #50
0
        protected override void OnCreateDeviceResources(WindowRenderTarget renderTarget)
        {
            base.OnCreateDeviceResources(renderTarget);
            // Create an array of gradient stops to put in the gradient stop
            // collection that will be used in the gradient brush.
            GradientStop[] stops = new GradientStop[] {
                new GradientStop(0, Color.FromARGB(Colors.Gold, 1)),
                new GradientStop(0.85f, Color.FromARGB(Colors.Orange, 1)),
                new GradientStop(1, Color.FromARGB(Colors.OrangeRed, 1))
            };

            using (GradientStopCollection gradiendStops = renderTarget.CreateGradientStopCollection(stops, Gamma.Gamma22, ExtendMode.Clamp))
            {
                // The center of the gradient is in the center of the box.
                // The gradient origin offset was set to zero(0, 0) or center in this case.
                this._radialGradientBrush = renderTarget.CreateRadialGradientBrush(
                    new RadialGradientBrushProperties(
                        new PointF(330, 330),
                        new PointF(140, 140),
                        140,
                        140),
                        BrushProperties.Default,
                        gradiendStops);
            }

            this._sceneBrush = renderTarget.CreateSolidColorBrush(Color.FromARGB(Colors.Black, 1));
            this._gridPatternBrush = renderTarget.CreateGridPatternBrush(new SizeF(10, 10), Color.FromARGB(1, 0.93f, 0.94f, 0.96f));
        }
Beispiel #51
0
        /// <summary>
        /// 获得焦点时边框的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtbox_GotFocus(object sender, RoutedEventArgs e)
        {
            SolidColorBrush brush = new SolidColorBrush(Color.FromRgb(232, 116, 57));

            b1.BorderBrush = brush;
        }
Beispiel #52
0
        //int i = 1;
        private async void GetConnectCassandras(Object source, EventArgs e)  // Метод в таймере для casmon и создания всех соединений по SSH
        {
            DispatcherTimer timer = (DispatcherTimer)source;

            if (null != timer.Tag)
            {
                return;
            }
            try
            {
                Task <List <Casmon> > t = Task <List <Casmon> > .Run(get_cass);

                timer.Tag = t;
                await t;
            }
            catch (Exception ass)
            {
                return;
            }
            finally
            {
                timer.Tag = null;
            }

            // получение файла casmon из начального соединения и извлечение всех доступных адресов
            List <Casmon> get_cass()
            {
                casmon_list.Clear();
                try
                {
                    using (SshCommand ddd = global.sshClients[0].RunCommand("cd /etc/cassandra/; /opt/rust-bin/casmon"))
                    {
                        string  res  = ddd.Result;
                        JObject eee  = JObject.Parse(res);
                        JArray  list = (JArray)eee["seeds"];
                        global.NameClasterCassandra = (string)eee["clusetr_name"];
                        string node  = "";
                        string check = "";
                        foreach (JObject content in list.Children <JObject>())
                        {
                            foreach (JProperty prop in content.Properties())
                            {
                                if (prop.Name.ToString() == "node")
                                {
                                    node = prop.Value.ToString();
                                }
                                else
                                {
                                    check = prop.Value.ToString();
                                }
                            }
                            casmon_list.Add(new Casmon(node, check));
                        }
                    }



                    // Проверяем доступность и меняем цвет
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                    {
                        if (global.casmons.Count == 0)
                        {
                            global.casmons = casmon_list;
                            radius_Elipse_Casmon(global.casmons);
                        }
                        else
                        {
                            foreach (Casmon cas in global.casmons)
                            {
                                if (cas.check == "False")
                                {
                                    //string tag = cas.node;
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;

                                            SolidColorBrush red          = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            SolidColorBrush border_color = (SolidColorBrush)border.Background;

                                            if (border.Tag.ToString() == cas.node.ToString() && red.Color != border_color.Color)
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Yellow, g_Yellow, b_Yellow));
                                                //global.casmons = t.Result;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;

                                            SolidColorBrush red          = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            SolidColorBrush border_color = (SolidColorBrush)border.Background;

                                            if (border.Tag.ToString() == cas.node.ToString() && red.Color != border_color.Color)
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_GreenE, g_GreenE, b_GreenE));
                                                //global.casmons = t.Result;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                catch (Exception ass)
                {
                    global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                    {
                        datagrid_system.ItemsSource  = null;
                        datagrid_system.SelectedItem = null;
                        datagrid_system.ItemsSource  = global.sshErrors;
                        datagrid_system.SelectedItem = global.sshErrors;
                    });
                }
                // делаем остальные соединения по ssh если их еще не сделали
                int m = global.sshClients.Count - 1;

                if (global.sshClients.Count < casmon_list.Count) // если количество соединений меньше возможных
                {
                    foreach (Casmon casmon in casmon_list)
                    {
                        if (casmon.node != global.host)
                        {
                            m++;
                            try
                            {
                                global.sshClients.Add(new SshClient(casmon.node, global.login, global.password));
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility = Visibility.Visible;
                                });
                                global.sshClients[m].Connect();
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility = Visibility.Hidden;
                                });
                                if (global.sshClients[m].IsConnected != true)
                                {
                                    //MessageBox.Show($"Соединение SSH по адресу {cassss[i].node} не получилось установить!");

                                    /*this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
                                     * {
                                     *  error_text.Text = $"Соединение SSH по адресу {casmon.node} не получилось установить! \n{COUNT}";
                                     * });
                                     * COUNT++;*/
                                }
                            }
                            catch (Exception ee)
                            {
                                //string host = global.sshClients[m].ConnectionInfo.Host;
                                string host = casmon.node;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            }
                                        }
                                    }
                                });



                                global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ee.ToString()));
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility       = Visibility.Hidden;
                                    datagrid_system.ItemsSource  = null;
                                    datagrid_system.SelectedItem = null;
                                    datagrid_system.ItemsSource  = global.sshErrors;
                                    datagrid_system.SelectedItem = global.sshErrors;
                                });
                            }
                        }
                    }
                }
                else if (global.sshClients.Count == casmon_list.Count)  // проверка на IsConnected
                {
                    foreach (SshClient ssh_client in global.sshClients)
                    {
                        if (ssh_client.IsConnected == false)
                        {
                            try
                            {
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility  = Visibility.Visible;
                                    image_Gif_System.Visibility = Visibility.Visible;
                                });
                                ssh_client.Connect();

                                // Если соединение установлено то красим в желтый
                                string host = ssh_client.ConnectionInfo.Host;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Yellow, g_Yellow, b_Yellow));
                                            }
                                        }
                                    }
                                });

                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility  = Visibility.Hidden;
                                    image_Gif_System.Visibility = Visibility.Hidden;
                                });
                            }
                            catch (Exception ass)
                            {
                                //======================================================================================================================
                                string host = ssh_client.ConnectionInfo.Host;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            }
                                        }
                                    }
                                });


                                global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility   = Visibility.Hidden;
                                    image_Gif_System.Visibility  = Visibility.Hidden;
                                    datagrid_system.ItemsSource  = null;
                                    datagrid_system.SelectedItem = null;
                                    datagrid_system.ItemsSource  = global.sshErrors;
                                    datagrid_system.SelectedItem = global.sshErrors;
                                });
                            }
                        }
                    }
                }

                global.sysmons.Clear();
                // получение всех sysmon файлов
                foreach (SshClient ssh in global.sshClients)
                {
                    disks.Clear();
                    try
                    {
                        using (SshCommand ddd = ssh.RunCommand("cd /etc/cassandra/; /opt/rust-bin/sysmon"))
                        {
                            string  res = ddd.Result;
                            JObject eee = JObject.Parse(res);

                            string host      = (string)eee["host"];
                            string ip        = (string)eee["ip"];
                            string os        = (string)eee["os"];
                            string version   = (string)eee["version"];
                            int    mem_total = (int)eee["mem_total"];
                            int    mem_used  = (int)eee["mem_used"];


                            JArray list        = (JArray)eee["disks"];
                            string name        = "";
                            string mount_point = "";
                            double total       = 0;
                            double used        = 0;
                            foreach (JObject content in list.Children <JObject>())
                            {
                                foreach (JProperty prop in content.Properties())
                                {
                                    if (prop.Name.ToString() == "name")
                                    {
                                        name = prop.Value.ToString();
                                    }
                                    else if (prop.Name.ToString() == "mount_point")
                                    {
                                        mount_point = prop.Value.ToString();
                                    }
                                    else if (prop.Name.ToString() == "total")
                                    {
                                        total = (double)prop.Value;
                                    }
                                    else if (prop.Name.ToString() == "used")
                                    {
                                        used = (double)prop.Value;
                                    }
                                }
                                disks.Add(new Disk(name, mount_point, total.ToString(), used.ToString()));
                            }
                            global.sysmons.Add(new Sysmon(host, ip, os, version, mem_total, mem_used, disks));
                            if (!setBoolNameClaster)  // устанавливаем имя кластера
                            {
                                nameClaster = global.sysmons[0].host;
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    cassandra_Name(nameClaster);
                                });
                                setBoolNameClaster = true;
                            }
                        }
                    }
                    catch (Exception ass)
                    {
                        global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                        {
                            datagrid_system.ItemsSource  = null;
                            datagrid_system.SelectedItem = null;
                            datagrid_system.ItemsSource  = global.sshErrors;
                            datagrid_system.SelectedItem = global.sshErrors;
                        });
                    }
                }
                return(casmon_list);
            }
        }
Beispiel #53
0
        /// <summary>
        /// 失去焦点时边框的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtbox_LostFocus(object sender, RoutedEventArgs e)
        {
            SolidColorBrush brush = new SolidColorBrush(Color.FromRgb(0xCA, 0xC3, 0xBA));

            b1.BorderBrush = brush;
        }
 public static SolidColorBrush GetBrush(this Color color)
 {
     var b = color.Tag as SolidColorBrush;
     if (b == null) {
         b = new SolidColorBrush (
             NativeColor.FromArgb (
             (byte)color.Alpha,
             (byte)color.Red,
             (byte)color.Green,
             (byte)color.Blue));
         color.Tag = b;
     }
     return b;
 }
Beispiel #55
0
        // ------------------------- CreateFirstVisual ------------------------
        /// <summary>
        ///   Creates content for the first visual sample.</summary>
        /// <param name="shouldMeasure">
        ///   true to remeasure the layout.</param>
        /// <returns>
        ///   The canvas containing the visual.</returns>
        public Canvas CreateFirstVisual(bool shouldMeasure)
        {
            Canvas canvas1 = new Canvas();

            canvas1.Width  = 96 * 8.5;
            canvas1.Height = 96 * 11;

            // Top-Left
            TextBlock label = new TextBlock();

            label.Foreground = Brushes.DarkBlue;
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 36.0;
            label.Text       = "TopLeft";
            Canvas.SetTop(label, 0);
            Canvas.SetLeft(label, 0);
            canvas1.Children.Add(label);

            // Bottom-Right
            label            = new TextBlock();
            label.Foreground = Brushes.Bisque;
            label.Text       = "BottomRight";
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 56.0;
            Canvas.SetTop(label, 750);
            Canvas.SetLeft(label, 520);
            canvas1.Children.Add(label);

            // Top-Right
            label            = new TextBlock();
            label.Foreground = Brushes.BurlyWood;
            label.Text       = "TopRight";
            label.FontFamily = new System.Windows.Media.FontFamily("CASTELLAR");
            label.FontSize   = 32.0;
            Canvas.SetTop(label, 0);
            Canvas.SetLeft(label, 520);
            canvas1.Children.Add(label);

            // Bottom-Left
            label            = new TextBlock();
            label.Foreground = Brushes.Cyan;
            label.Text       = "BottomLeft";
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 18.0;
            Canvas.SetTop(label, 750);
            Canvas.SetLeft(label, 0);
            canvas1.Children.Add(label);

            // Adding a rectangle to the page
            Rectangle firstRectangle = new Rectangle();

            firstRectangle.Fill = new SolidColorBrush(Colors.Red);
            Thickness thick = new Thickness();

            thick.Left            = 150;
            thick.Top             = 150;
            firstRectangle.Margin = thick;
            firstRectangle.Width  = 300;
            firstRectangle.Height = 300;
            canvas1.Children.Add(firstRectangle);

            //Add a button to the page
            Button firstButton = new Button();

            firstButton.Background      = Brushes.LightYellow;
            firstButton.BorderBrush     = new SolidColorBrush(Colors.Black);
            firstButton.BorderThickness = new Thickness(4);
            firstButton.Content         = "I am button 1...";
            firstButton.FontSize        = 16.0;
            thick.Left         = 80;
            thick.Top          = 250;
            firstButton.Margin = thick;
            canvas1.Children.Add(firstButton);

            // Add an Ellipse
            Ellipse         firstEllipse         = new Ellipse();
            SolidColorBrush firstSolidColorBrush = new SolidColorBrush(Colors.DarkCyan);

            firstSolidColorBrush.Opacity = 0.7;
            firstEllipse.Fill            = firstSolidColorBrush;
            SetEllipse(firstEllipse, 500, 350, 120, 250);
            canvas1.Children.Add(firstEllipse);

            // Add a Polygon
            Polygon polygon = new Polygon();

            polygon.Fill    = Brushes.Bisque;
            polygon.Opacity = 0.2;
            PointCollection points = new PointCollection();

            points.Add(new Point(50, 0));
            points.Add(new Point(10, 30));
            points.Add(new Point(30, 170));
            points.Add(new Point(90, 40));
            points.Add(new Point(230, 180));
            points.Add(new Point(200, 60));
            points.Add(new Point(240, 10));
            points.Add(new Point(70, 130));
            polygon.Points = points;
            polygon.Stroke = Brushes.Navy;
            Canvas.SetTop(polygon, 300);
            Canvas.SetLeft(polygon, 160);
            canvas1.Children.Add(polygon);

            if (shouldMeasure)
            {
                Size sz = new Size(8.5 * 96, 11 * 96);
                canvas1.Measure(sz);
                canvas1.Arrange(new Rect(new Point(), sz));
                canvas1.UpdateLayout();
            }

            return(canvas1);
        }// end:CreateFirstVisual()
Beispiel #56
0
 private void AddSeries(GearedValues <long> values, string title, Color color, double strokeThickness, SolidColorBrush fillBrush, DoubleCollection strokeDashArray = null)
 {
     cartesianChart1.Series.Add(new GLineSeries
     {
         Values          = values,
         Title           = title,
         Stroke          = new SolidColorBrush(color),
         Fill            = fillBrush,
         StrokeThickness = strokeThickness,
         StrokeDashArray = strokeDashArray,
         PointGeometry   = null //use a null geometry when you have many series
     });
 }
Beispiel #57
0
 public void FillColor(Color color)
 {
     ShapeColor = new SolidColorBrush(color);
 }
Beispiel #58
0
 /// <summary>
 /// Initializes static members of the <see cref="Brushes"/> class.
 /// </summary>
 static Brushes()
 {
     AliceBlue = new SolidColorBrush(Colors.AliceBlue);
     AntiqueWhite = new SolidColorBrush(Colors.AntiqueWhite);
     Aqua = new SolidColorBrush(Colors.Aqua);
     Aquamarine = new SolidColorBrush(Colors.Aquamarine);
     Azure = new SolidColorBrush(Colors.Azure);
     Beige = new SolidColorBrush(Colors.Beige);
     Bisque = new SolidColorBrush(Colors.Bisque);
     Black = new SolidColorBrush(Colors.Black);
     BlanchedAlmond = new SolidColorBrush(Colors.BlanchedAlmond);
     Blue = new SolidColorBrush(Colors.Blue);
     BlueViolet = new SolidColorBrush(Colors.BlueViolet);
     Brown = new SolidColorBrush(Colors.Brown);
     BurlyWood = new SolidColorBrush(Colors.BurlyWood);
     CadetBlue = new SolidColorBrush(Colors.CadetBlue);
     Chartreuse = new SolidColorBrush(Colors.Chartreuse);
     Chocolate = new SolidColorBrush(Colors.Chocolate);
     Coral = new SolidColorBrush(Colors.Coral);
     CornflowerBlue = new SolidColorBrush(Colors.CornflowerBlue);
     Cornsilk = new SolidColorBrush(Colors.Cornsilk);
     Crimson = new SolidColorBrush(Colors.Crimson);
     Cyan = new SolidColorBrush(Colors.Cyan);
     DarkBlue = new SolidColorBrush(Colors.DarkBlue);
     DarkCyan = new SolidColorBrush(Colors.DarkCyan);
     DarkGoldenrod = new SolidColorBrush(Colors.DarkGoldenrod);
     DarkGray = new SolidColorBrush(Colors.DarkGray);
     DarkGreen = new SolidColorBrush(Colors.DarkGreen);
     DarkKhaki = new SolidColorBrush(Colors.DarkKhaki);
     DarkMagenta = new SolidColorBrush(Colors.DarkMagenta);
     DarkOliveGreen = new SolidColorBrush(Colors.DarkOliveGreen);
     DarkOrange = new SolidColorBrush(Colors.DarkOrange);
     DarkOrchid = new SolidColorBrush(Colors.DarkOrchid);
     DarkRed = new SolidColorBrush(Colors.DarkRed);
     DarkSalmon = new SolidColorBrush(Colors.DarkSalmon);
     DarkSeaGreen = new SolidColorBrush(Colors.DarkSeaGreen);
     DarkSlateBlue = new SolidColorBrush(Colors.DarkSlateBlue);
     DarkSlateGray = new SolidColorBrush(Colors.DarkSlateGray);
     DarkTurquoise = new SolidColorBrush(Colors.DarkTurquoise);
     DarkViolet = new SolidColorBrush(Colors.DarkViolet);
     DeepPink = new SolidColorBrush(Colors.DeepPink);
     DeepSkyBlue = new SolidColorBrush(Colors.DeepSkyBlue);
     DimGray = new SolidColorBrush(Colors.DimGray);
     DodgerBlue = new SolidColorBrush(Colors.DodgerBlue);
     Firebrick = new SolidColorBrush(Colors.Firebrick);
     FloralWhite = new SolidColorBrush(Colors.FloralWhite);
     ForestGreen = new SolidColorBrush(Colors.ForestGreen);
     Fuchsia = new SolidColorBrush(Colors.Fuchsia);
     Gainsboro = new SolidColorBrush(Colors.Gainsboro);
     GhostWhite = new SolidColorBrush(Colors.GhostWhite);
     Gold = new SolidColorBrush(Colors.Gold);
     Goldenrod = new SolidColorBrush(Colors.Goldenrod);
     Gray = new SolidColorBrush(Colors.Gray);
     Green = new SolidColorBrush(Colors.Green);
     GreenYellow = new SolidColorBrush(Colors.GreenYellow);
     Honeydew = new SolidColorBrush(Colors.Honeydew);
     HotPink = new SolidColorBrush(Colors.HotPink);
     IndianRed = new SolidColorBrush(Colors.IndianRed);
     Indigo = new SolidColorBrush(Colors.Indigo);
     Ivory = new SolidColorBrush(Colors.Ivory);
     Khaki = new SolidColorBrush(Colors.Khaki);
     Lavender = new SolidColorBrush(Colors.Lavender);
     LavenderBlush = new SolidColorBrush(Colors.LavenderBlush);
     LawnGreen = new SolidColorBrush(Colors.LawnGreen);
     LemonChiffon = new SolidColorBrush(Colors.LemonChiffon);
     LightBlue = new SolidColorBrush(Colors.LightBlue);
     LightCoral = new SolidColorBrush(Colors.LightCoral);
     LightCyan = new SolidColorBrush(Colors.LightCyan);
     LightGoldenrodYellow = new SolidColorBrush(Colors.LightGoldenrodYellow);
     LightGray = new SolidColorBrush(Colors.LightGray);
     LightGreen = new SolidColorBrush(Colors.LightGreen);
     LightPink = new SolidColorBrush(Colors.LightPink);
     LightSalmon = new SolidColorBrush(Colors.LightSalmon);
     LightSeaGreen = new SolidColorBrush(Colors.LightSeaGreen);
     LightSkyBlue = new SolidColorBrush(Colors.LightSkyBlue);
     LightSlateGray = new SolidColorBrush(Colors.LightSlateGray);
     LightSteelBlue = new SolidColorBrush(Colors.LightSteelBlue);
     LightYellow = new SolidColorBrush(Colors.LightYellow);
     Lime = new SolidColorBrush(Colors.Lime);
     LimeGreen = new SolidColorBrush(Colors.LimeGreen);
     Linen = new SolidColorBrush(Colors.Linen);
     Magenta = new SolidColorBrush(Colors.Magenta);
     Maroon = new SolidColorBrush(Colors.Maroon);
     MediumAquamarine = new SolidColorBrush(Colors.MediumAquamarine);
     MediumBlue = new SolidColorBrush(Colors.MediumBlue);
     MediumOrchid = new SolidColorBrush(Colors.MediumOrchid);
     MediumPurple = new SolidColorBrush(Colors.MediumPurple);
     MediumSeaGreen = new SolidColorBrush(Colors.MediumSeaGreen);
     MediumSlateBlue = new SolidColorBrush(Colors.MediumSlateBlue);
     MediumSpringGreen = new SolidColorBrush(Colors.MediumSpringGreen);
     MediumTurquoise = new SolidColorBrush(Colors.MediumTurquoise);
     MediumVioletRed = new SolidColorBrush(Colors.MediumVioletRed);
     MidnightBlue = new SolidColorBrush(Colors.MidnightBlue);
     MintCream = new SolidColorBrush(Colors.MintCream);
     MistyRose = new SolidColorBrush(Colors.MistyRose);
     Moccasin = new SolidColorBrush(Colors.Moccasin);
     NavajoWhite = new SolidColorBrush(Colors.NavajoWhite);
     Navy = new SolidColorBrush(Colors.Navy);
     OldLace = new SolidColorBrush(Colors.OldLace);
     Olive = new SolidColorBrush(Colors.Olive);
     OliveDrab = new SolidColorBrush(Colors.OliveDrab);
     Orange = new SolidColorBrush(Colors.Orange);
     OrangeRed = new SolidColorBrush(Colors.OrangeRed);
     Orchid = new SolidColorBrush(Colors.Orchid);
     PaleGoldenrod = new SolidColorBrush(Colors.PaleGoldenrod);
     PaleGreen = new SolidColorBrush(Colors.PaleGreen);
     PaleTurquoise = new SolidColorBrush(Colors.PaleTurquoise);
     PaleVioletRed = new SolidColorBrush(Colors.PaleVioletRed);
     PapayaWhip = new SolidColorBrush(Colors.PapayaWhip);
     PeachPuff = new SolidColorBrush(Colors.PeachPuff);
     Peru = new SolidColorBrush(Colors.Peru);
     Pink = new SolidColorBrush(Colors.Pink);
     Plum = new SolidColorBrush(Colors.Plum);
     PowderBlue = new SolidColorBrush(Colors.PowderBlue);
     Purple = new SolidColorBrush(Colors.Purple);
     Red = new SolidColorBrush(Colors.Red);
     RosyBrown = new SolidColorBrush(Colors.RosyBrown);
     RoyalBlue = new SolidColorBrush(Colors.RoyalBlue);
     SaddleBrown = new SolidColorBrush(Colors.SaddleBrown);
     Salmon = new SolidColorBrush(Colors.Salmon);
     SandyBrown = new SolidColorBrush(Colors.SandyBrown);
     SeaGreen = new SolidColorBrush(Colors.SeaGreen);
     SeaShell = new SolidColorBrush(Colors.SeaShell);
     Sienna = new SolidColorBrush(Colors.Sienna);
     Silver = new SolidColorBrush(Colors.Silver);
     SkyBlue = new SolidColorBrush(Colors.SkyBlue);
     SlateBlue = new SolidColorBrush(Colors.SlateBlue);
     SlateGray = new SolidColorBrush(Colors.SlateGray);
     Snow = new SolidColorBrush(Colors.Snow);
     SpringGreen = new SolidColorBrush(Colors.SpringGreen);
     SteelBlue = new SolidColorBrush(Colors.SteelBlue);
     Tan = new SolidColorBrush(Colors.Tan);
     Teal = new SolidColorBrush(Colors.Teal);
     Thistle = new SolidColorBrush(Colors.Thistle);
     Tomato = new SolidColorBrush(Colors.Tomato);
     Transparent = new SolidColorBrush(Colors.Transparent);
     Turquoise = new SolidColorBrush(Colors.Turquoise);
     Violet = new SolidColorBrush(Colors.Violet);
     Wheat = new SolidColorBrush(Colors.Wheat);
     White = new SolidColorBrush(Colors.White);
     WhiteSmoke = new SolidColorBrush(Colors.WhiteSmoke);
     Yellow = new SolidColorBrush(Colors.Yellow);
     YellowGreen = new SolidColorBrush(Colors.YellowGreen);
 }
Beispiel #59
0
        public XamlCanvas()
        {
            Background = new SolidColorBrush (NativeColors.Transparent);

            MinFps = 4;
            MaxFps = 30;
            Continuous = true;

            _drawTimer = new DispatcherTimer();
            _drawTimer.Tick += DrawTick;

            Unloaded += HandleUnloaded;
            Loaded += HandleLoaded;
            LayoutUpdated += delegate { HandleLayoutUpdated (); };
        }
Beispiel #60
-1
        public PDirect2DRenderer(IntPtr winHandle)
        {
            fWindowHandle = winHandle;
            CreateFactories();
            CreateDeviceResources();

            Graphics = hwndRenderTarget;

            fStrokeBrush = Graphics.CreateSolidColorBrush(new ColorF(0, 0, 0, 1));
            fFillBrush = Graphics.CreateSolidColorBrush(new ColorF(1, 1, 1, 1));
        }