Example #1
0
        /// <summary>
        /// Copy given style to initialize a new instance.
        /// </summary>
        /// <param name="style">A Style from which property values are to be copied.</param>
        public GraphicStyle(Style style, bool scaling = true) : base(style)
        {
            float scaleFactor = 1f;

            if (scaling)
            {
                using (var bitmap = new Drawing.Bitmap(1, 1))
                    using (var graphics = Drawing.Graphics.FromImage(bitmap))
                    {
                        scaleFactor = 96 / graphics.DpiY;
                    }
            }

            if (string.IsNullOrEmpty(Name))
            {
                // TODO: is this needed here? should do in styledialog?
                Name = "Style-" + new Random().Next(1000, 9999).ToString();
            }

            var fontStyle = Drawing.FontStyle.Regular;

            if (style.IsBold)
            {
                fontStyle |= Drawing.FontStyle.Bold;
            }
            if (style.IsItalic)
            {
                fontStyle |= Drawing.FontStyle.Italic;
            }
            if (style.IsUnderline)
            {
                fontStyle |= Drawing.FontStyle.Underline;
            }
            if (style.IsStrikethrough)
            {
                fontStyle |= Drawing.FontStyle.Strikeout;
            }

            try
            {
                Font = new Drawing.Font(
                    FontFamily, (float)fontSize * scaleFactor, fontStyle);
            }
            catch (Exception exc)
            {
                logger.WriteLine(
                    $"error creating font({FontFamily}, {fontSize}, {fontStyle})", exc);

                Font = new Drawing.Font(
                    DefaultFontFamily, (float)DefaultFontSize * scaleFactor, fontStyle);
            }

            try
            {
                Foreground = Color.Equals(Automatic)
                                        ? Drawing.Color.Black
                                        : Drawing.ColorTranslator.FromHtml(Color);
            }
            catch (Exception exc)
            {
                logger.WriteLine($"error translating color {Color}", exc);
                Foreground = Drawing.Color.Black;
            }

            try
            {
                Background = Highlight.Equals(Automatic)
                                        ? Drawing.Color.Transparent
                                        : Drawing.ColorTranslator.FromHtml(Highlight);
            }
            catch (Exception exc)
            {
                logger.WriteLine($"error translating highlight {Highlight}", exc);
                Background = Drawing.Color.Transparent;
            }
        }