Exemplo n.º 1
0
        /// <summary>
        /// 计算文本显示宽、高
        /// </summary>
        public static MeasureSize MeasureText(string text,
                                              System.Windows.Media.FontFamily fontFamily,
                                              System.Windows.FontStyle fontStyle,
                                              System.Windows.FontWeight fontWeight,
                                              System.Windows.FontStretch fontStretch,
                                              double fontSize)
        {
            System.Windows.Media.Typeface      typeface = new System.Windows.Media.Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            System.Windows.Media.GlyphTypeface glyphTypeface;
            if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
            {
                return(MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize));
            }
            double totalWidth = 0;
            double height     = 0;

            for (int n = 0; n < text.Length; n++)
            {
                ushort glyphIndex  = glyphTypeface.CharacterToGlyphMap[text[n]];
                double width       = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
                double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex] * fontSize;
                if (glyphHeight > height)
                {
                    height = glyphHeight;
                }
                totalWidth += width;
            }
            return(new MeasureSize(totalWidth, height));
        }
Exemplo n.º 2
0
        TransferToGraphDrawer
        (
            GraphDrawer graphDrawer
        )
        {
            Debug.Assert(graphDrawer != null);
            AssertValid();

            Font oFont = this.Font;

            System.Windows.Media.Typeface oTypeface =
                WpfGraphicsUtil.FontToTypeface(oFont);

            Double dFontSize = WpfGraphicsUtil.WindowsFormsFontSizeToWpfFontSize(
                oFont.Size);

            VertexDrawer oVertexDrawer = graphDrawer.VertexDrawer;

            oVertexDrawer.SetFont(oTypeface, dFontSize);

            oVertexDrawer.LabelFillColor =
                WpfGraphicsUtil.ColorToWpfColor(this.VertexLabelFillColor);

            oVertexDrawer.LabelPosition      = this.VertexLabelPosition;
            oVertexDrawer.MaximumLabelLength = this.VertexLabelMaximumLength;

            EdgeDrawer oEdgeDrawer = graphDrawer.EdgeDrawer;

            oEdgeDrawer.SetFont(oTypeface, dFontSize);
            oEdgeDrawer.MaximumLabelLength = this.EdgeLabelMaximumLength;
        }
        public override IText AddText(string text, double fontSize, System.Windows.Media.SolidColorBrush brush)
        {
            if (cachedTypeface == null)
            {
                cachedTypeface = CreateTypeface();
            }
            var textFormat = d2d.DirectWriteFactory.CreateTextFormat(
                cachedTypeface.FontFamily.Source,
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                (float)fontSize);

            textFormat.TextAlignment      = TextAlignment.Leading;
            textFormat.ParagraphAlignment = ParagraphAlignment.Near;

            var textLayout = d2d.DirectWriteFactory.CreateTextLayout(
                text,
                textFormat,
                300, 100);

            MyText myText = new MyText {
                parent     = this,
                textFormat = textFormat,
                textLayout = textLayout,
                color      = Color.FromRGB(brush.Color.R / 255f, brush.Color.G / 255f, brush.Color.B / 255f)
            };

            texts.Add(myText);
            return(myText);
        }
        public override IText AddText(string text, double fontSize, System.Windows.Media.SolidColorBrush brush)
        {
            if (cachedTypeface == null) {
                cachedTypeface = CreateTypeface();
            }
            var textFormat = d2d.DirectWriteFactory.CreateTextFormat(
                cachedTypeface.FontFamily.Source,
                FontWeight.Normal,
                FontStyle.Normal,
                FontStretch.Normal,
                (float)fontSize);
            textFormat.TextAlignment = TextAlignment.Leading;
            textFormat.ParagraphAlignment = ParagraphAlignment.Near;

            var textLayout = d2d.DirectWriteFactory.CreateTextLayout(
                text,
                textFormat,
                300, 100);

            MyText myText = new MyText {
                parent = this,
                textFormat = textFormat,
                textLayout = textLayout,
                color = Color.FromRGB(brush.Color.R / 255f, brush.Color.G / 255f, brush.Color.B / 255f)
            };
            texts.Add(myText);
            return myText;
        }
Exemplo n.º 5
0
 public static System.Windows.Size MeasureTextBlockSize(TextBlock textblock)
 {
     System.Windows.Media.Typeface      typeFace      = new System.Windows.Media.Typeface(textblock.FontFamily, textblock.FontStyle, textblock.FontWeight, textblock.FontStretch);
     System.Windows.Media.FormattedText formattedText = new System.Windows.Media.FormattedText(textblock.Text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                                                                               typeFace, textblock.FontSize, textblock.Foreground);
     return(new System.Windows.Size(formattedText.Width, formattedText.Height));
 }
Exemplo n.º 6
0
        public override IText AddText(string text, double fontSize, System.Windows.Media.SolidColorBrush brush)
        {
            if (cachedTypeface == null)
            {
                cachedTypeface = CreateTypeface();
            }

            LOGFONT logfont = new LOGFONT();

            logfont.lfFaceName = cachedTypeface.FontFamily.Source;
            logfont.lfHeight   = -(int)fontSize;
            //logfont.lfOutPrecision = 4;
            //logfont.lfQuality = 5;

            MyText myText = new MyText {
                parent = this,
                text   = text,
                color  = brush.Color.R | (brush.Color.G << 8) | (brush.Color.B << 16),
                font   = CreateFontIndirect(ref logfont)
            };

            //myText.brush = new SolidBrush(myText.color);

            texts.Add(myText);
            return(myText);
        }
Exemplo n.º 7
0
 internal static WpfTypeface TryCreateTypeface(string name, XFontStyle style, out WpfFontFamily fontFamily)
 {
     if (Singleton._fontFamilies.TryGetValue(name, out fontFamily))
     {
         WpfTypeface typeface = FontHelper.CreateTypeface(fontFamily, style);
         return(typeface);
     }
     return(null);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XFont"/> class from a System.Windows.Media.Typeface.
 /// </summary>
 /// <param name="typeface">The System.Windows.Media.Typeface.</param>
 /// <param name="emSize">The em size.</param>
 /// <param name="pdfOptions">Additional PDF options.</param>
 public XFont(WpfTypeface typeface, double emSize, XPdfFontOptions pdfOptions)
 {
     _wpfTypeface = typeface;
     //Debug.Assert(font.Name == font.FontFamily.Name);
     //_familyName = font.Name;
     _emSize     = emSize;
     _pdfOptions = pdfOptions;
     InitializeFromWpf();
 }
Exemplo n.º 9
0
 private static byte[] GetFontWithWPF(Font aFont, byte[] FFontData)
 {
     System.Windows.Media.Typeface      fm = new System.Windows.Media.Typeface(GetWpfFontFamily(aFont), GetWpfStyle(aFont), GetWpfFontWeight(aFont), GetWpfFontStretch(aFont));
     System.Windows.Media.GlyphTypeface gt;
     if (fm.TryGetGlyphTypeface(out gt))
     {
         using (Stream st = gt.GetFontStream())
         {
             FFontData = new byte[st.Length];
             st.Read(FFontData, 0, FFontData.Length);
         }
     }
     return(FFontData);
 }
Exemplo n.º 10
0
        FontToTypefaceAndFontSize
        (
            Font oFont,
            out System.Windows.Media.Typeface oTypeface,
            out Double dFontSize
        )
        {
            Debug.Assert(oFont != null);
            AssertValid();

            oTypeface = WpfGraphicsUtil.FontToTypeface(oFont);

            dFontSize = WpfGraphicsUtil.SystemDrawingFontSizeToWpfFontSize(
                oFont.Size);
        }
        public override IText AddText(string text, double fontSize, System.Windows.Media.SolidColorBrush brush)
        {
            if (cachedTypeface == null)
            {
                cachedTypeface = CreateTypeface();
            }

            MyText myText = new MyText {
                parent = this,
                text   = text,
                color  = Color.FromArgb(brush.Color.R, brush.Color.G, brush.Color.B),
                font   = new Font(cachedTypeface.FontFamily.Source, (float)(fontSize / 96 * 72), FontStyle.Regular),
            };

            myText.brush = new SolidBrush(myText.color);
            texts.Add(myText);
            return(myText);
        }
        private static Shape CreateTextShape(string text, double placeX, double placeY, double fontSize, System.Windows.Media.Color color)
        {
            Shape textShape;

            System.Windows.Media.FontFamily fontFamily = new System.Windows.Media.FontFamily("Times New Roman");
            Typeface typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Bold, new FontStretch());

            FormattedText fText = new FormattedText(text, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, fontSize, System.Windows.Media.Brushes.Black);

            System.Windows.Point textPosition1;
            textPosition1 = new System.Windows.Point(placeX, placeY);
            Path path = new Path();

            path.Data = fText.BuildGeometry(textPosition1);
            path.Fill = new SolidColorBrush(color);
            textShape = path;
            return(textShape);
        }
Exemplo n.º 13
0
        public System.Windows.Media.Typeface GetTypeface(string name, System.Windows.FontWeight weight,
                                                         System.Windows.FontStyle style, System.Windows.FontStretch stretch)
        {
            List <System.Windows.Media.Typeface> list;

            if (!typefaces.TryGetValue(name, out list))
            {
                this.typefaces[name] = list = new List <System.Windows.Media.Typeface>();
            }

            var typeface = list.FirstOrDefault(t => t.Weight == weight && t.Style == style);

            if (typeface == null)
            {
                list.Add(typeface = new System.Windows.Media.Typeface(new System.Windows.Media.FontFamily(name), style, weight, stretch));
            }

            return(typeface);
        }
        /// <summary>Draw Text to canvas according coordinates and label</summary>
        public void DrawText(string label, float x, float y, float xmin, float ymin, float xmax, float ymax)
        {
            if (_fillColor.Color.A > 0)
            {
                // Create formatted text in a particular font at a particular size
                var typeFace = new System.Windows.Media.Typeface(_fontFamily, _fontStyle, _fontWeight, _fontStretch);
                var ft       = new System.Windows.Media.FormattedText
                               (
                    label, System.Globalization.CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight, typeFace, _fontSize, _fillColor
                               );

                ft.TextAlignment = TextAlignment.Left;

                // Draw the text
                var clipped = PushRenderStates();
                _drawingContext.DrawText(ft, new System.Windows.Point(x, y - _baseline));
                PopRenderStates(clipped);
            }
        }
        public override IText AddText(string text, double fontSize, System.Windows.Media.SolidColorBrush brush)
        {
            if (cachedTypeface == null) {
                cachedTypeface = CreateTypeface();
            }

            LOGFONT logfont = new LOGFONT();
            logfont.lfFaceName = cachedTypeface.FontFamily.Source;
            logfont.lfHeight = -(int)fontSize;
            //logfont.lfOutPrecision = 4;
            //logfont.lfQuality = 5;

            MyText myText = new MyText {
                parent = this,
                text = text,
                color = brush.Color.R | (brush.Color.G << 8) | (brush.Color.B << 16),
                font = CreateFontIndirect(ref logfont)
            };
            //myText.brush = new SolidBrush(myText.color);

            texts.Add(myText);
            return myText;
        }
Exemplo n.º 16
0
        private void Create_WPF_Window()
        {
            //int scrnHeight = Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight);
            int scrnWidth = Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth);

            /****************************
            * WPF Window
            ****************************/
            WPFControl1 n = new WPFControl1();

            n.Left   = GetCursorPosition().X;
            n.Top    = GetCursorPosition().Y + 5;
            n.Height = 200;
            n.Width  = 450;
            n.Show();


            /****************************
            * Label for WPF content
            ****************************/
            System.Windows.Controls.Label _fs = new System.Windows.Controls.Label();
            _fs.Foreground = System.Windows.Media.Brushes.White;
            //_fs.Foreground = System.Windows.Media.Brushes.
            _fs.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(SMS_ToolTip.fontColor[0], SMS_ToolTip.fontColor[1], SMS_ToolTip.fontColor[2], SMS_ToolTip.fontColor[3]));
            _fs.FontFamily = new System.Windows.Media.FontFamily("Segoe UI");
            _fs.FontSize   = 18;
            _fs.FontWeight = System.Windows.FontWeights.Bold;
            _fs.Effect     = new DropShadowEffect
            {
                Color = new System.Windows.Media.Color {
                    A = 255, R = 0, G = 0, B = 0
                },
                Direction   = 0,
                ShadowDepth = 0,
                Opacity     = 1
            };
            _fs.Opacity = 1;
            n.Content   = _fs;


            /****************************
            * Timer to lock window to
            * cursor pos and keep
            * label.text up to date
            ****************************/
            System.Windows.Forms.Timer _t1 = new System.Windows.Forms.Timer();
            int _tt = 0;

            _t1.Tick += (sender, e) =>
            {
                if (_tt >= 220)
                {
                    _t1.Enabled = false;
                    DoubleAnimation anim = new DoubleAnimation(0, (System.Windows.Duration)TimeSpan.FromSeconds(1));
                    anim.Completed += (s, _) => n.Close();
                    n.BeginAnimation(System.Windows.UIElement.OpacityProperty, anim);

                    return;
                }
                string[] lines = ((RichTextBox)Threads[SMS_ToolTip.SelectedTab].richBox).Lines;
                int      v;
                string   sample;

                _fs.Content = string.Format("Name: {0}\r\nRecommended Value: {1}", lines.Length > 1 ? lines[1] : "E", ((Label)Threads[SMS_ToolTip.SelectedTab].valueBox).Text);
                v           = string.Format("Name: {0}", lines.Length > 1 ? lines[1] : "E").Length > string.Format("Recommended Value: {0}", ((Label)Threads[SMS_ToolTip.SelectedTab].valueBox).Text).Length ? 1 : 2;

                if (v == 2)
                {
                    sample = string.Format("Recommended Value: {0}", ((Label)Threads[SMS_ToolTip.SelectedTab].valueBox).Text);
                }
                else
                {
                    sample = string.Format("Name: {0}", lines.Length > 1 ? lines[1] : "E");
                }


                System.Windows.Media.Typeface      myTypeface = new System.Windows.Media.Typeface("Segoe UI");
                System.Windows.Media.FormattedText ft         = new System.Windows.Media.FormattedText(sample, CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, myTypeface, 20, System.Windows.Media.Brushes.White);

                if ((GetCursorPosition().X + ft.Width) + 25 > scrnWidth)
                {
                    n.Left = (GetCursorPosition().X - 25) - ft.Width;
                    n.Top  = GetCursorPosition().Y;
                }
                else
                {
                    n.Left = GetCursorPosition().X + 25;
                    n.Top  = GetCursorPosition().Y;
                }
                _tt++;
            };
            _t1.Interval = 10;
            _t1.Enabled  = true;
        }
Exemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XFont" /> class from a System.Windows.Media.Typeface.
 /// </summary>
 /// <param name="typeface">The System.Windows.Media.Typeface.</param>
 /// <param name="emSize">The em size.</param>
 public XFont(WpfTypeface typeface, double emSize)
     : this(typeface, emSize, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
 {
 }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XFont" /> class from a System.Windows.Media.Typeface.
 /// </summary>
 /// <param name="typeface">The System.Windows.Media.Typeface.</param>
 /// <param name="emSize">The em size.</param>
 public XFont(WpfTypeface typeface, double emSize)
     : this(typeface, emSize, new XPdfFontOptions(GlobalFontSettings.DefaultFontEncoding))
 { }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XFont"/> class from a System.Windows.Media.Typeface.
 /// </summary>
 /// <param name="typeface">The System.Windows.Media.Typeface.</param>
 /// <param name="emSize">The em size.</param>
 /// <param name="pdfOptions">Additional PDF options.</param>
 public XFont(WpfTypeface typeface, double emSize, XPdfFontOptions pdfOptions)
 {
     _wpfTypeface = typeface;
     //Debug.Assert(font.Name == font.FontFamily.Name);
     //_familyName = font.Name;
     _emSize = emSize;
     _pdfOptions = pdfOptions;
     InitializeFromWpf();
 }
Exemplo n.º 20
0
        private void ConvertButton_Click(object sender, EventArgs e)
        {
            if (OutputFileName == null || OutputFileName == "")
            {
                MessageBox.Show("Invalid File Name!");
            }
            else
            {
                //FileStream str;
                FileStream final;
                dynamic strm;

                #region Already Exists
                if (File.Exists(OutputFileName))
                {
                    if (MessageBox.Show("A file at '" + OutputFileName + "' already exists! Would you like to overwrite it?", "File Already Exists", MessageBoxButtons.YesNoCancel) == System.Windows.Forms.DialogResult.Yes)
                    {

                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    File.Create(OutputFileName).Close();
                }
                #endregion

                #region Compression Config
                //if (CompressionMode == CompressionType.Deflate)
                //{
                //    str = new FileStream(OutputFileName, FileMode.Truncate);
                //    strm = new DeflateStream(str, System.IO.Compression.CompressionMode.Compress);
                //    final = null;
                //}
                //else if (CompressionMode == CompressionType.GZip)
                //{
                //    str = new FileStream(OutputFileName, FileMode.Truncate);
                //    strm = new GZipStream(str, System.IO.Compression.CompressionMode.Compress);
                //    final = null;
                //}
                if (CompressionMode == CompressionType.LZMA)
                {
                    if (File.Exists(OutputFileName + ".uncmpr"))
                    {
                        File.Delete(OutputFileName + ".uncmpr");
                    }
                    strm = File.Create(OutputFileName + ".uncmpr");
                    final = new FileStream(OutputFileName, FileMode.Truncate);
                }
                else
                {
                    strm = new FileStream(OutputFileName, FileMode.Truncate);
                    final = null;
                }
                #endregion

                BinaryWriter br = new BinaryWriter(strm);

                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0); // Write the 8 empty bytes of the header
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);

                byte[] buffer;
                br.Write((UInt16)47); // write the format version.


                string FontName = (string)FontComboBox.SelectedItem;

                buffer = ASCIIEncoding.ASCII.GetBytes(FontName);
                int i = 256 - buffer.Length;
                if (i < 0)
                {
                    throw new Exception("Font Name is to long!");
                }
                else
                {
                    br.Write(buffer);
                    for (int i2 = 0; i2 < i; i2++)
                    {
                        br.Write((byte)0); // Fill the rest of the 256 bytes.
                    }
                }

                System.Windows.Media.Typeface t = new System.Windows.Media.Typeface(FontName);
                System.Windows.Media.GlyphTypeface glyph;
                if (t.TryGetGlyphTypeface(out glyph))
                {
                    t = null;
                    IDictionary<int, ushort> charKeyMap = (IDictionary<int, ushort>)glyph.CharacterToGlyphMap;
                    glyph = null;
                    SortedSet<int> chars = new SortedSet<int>();
                    foreach (KeyValuePair<int, ushort> c in charKeyMap)
                    {
                        chars.Add(c.Key);
                    }
                    charKeyMap = null;
                    Font f = new Font(FontName, 128, GraphicsUnit.Pixel);

                    UInt64 charsToWrite = (ulong)chars.Count;// *16;
                    br.Write(charsToWrite); // Write the number of chars to read.

                    int prevChar = 0;

                    for (byte style = 0; style < 1; style++)
                    {
                        f = new Font(FontName, 64, (FontStyle)style, GraphicsUnit.Pixel);
                        foreach (int ch in chars)
                        {
                            Bitmap Backend = new Bitmap(1, 1);
                            Graphics g = Graphics.FromImage(Backend);
                            SizeF sz = g.MeasureString(new String(new char[] { (char)ch }), f);
                            byte height = (byte)Math.Ceiling(sz.Height + 2);
                            byte width = (byte)Math.Ceiling(sz.Width + 4);
                            Backend = new Bitmap(width, height);
                            g = Graphics.FromImage(Backend);
                            g.Clear(Color.White);

                            g.DrawString(new String(new char[] { (char)ch }), f, new SolidBrush(Color.Black), 2, 2);
                            g.Flush(System.Drawing.Drawing2D.FlushIntention.Flush);
                            if (prevChar + 1 == ch)
                            {
                                br.Write((byte)255); // write that it's incremented from the previous char.
                            }
                            else
                            {
                                br.Write((byte)0); // write that it's not incremented from the previous char.
                                br.Write((UInt32)ch); // Write the char number.
                            }
                            pictureBox1.Image = Backend;
                            pictureBox1.Refresh();

                            br.Write((byte)style); // write it's style
                            br.Write((byte)height); // write the height
                            br.Write((byte)width); // write the width
                            buffer = ConvertToByteArray(Backend);
                            br.Write(buffer);
                            prevChar = ch;
                        }
                        strm.Flush();
                        System.GC.Collect();
                    }

                    if (CompressionMode == CompressionType.LZMA)
                    {
                        strm.Position = 0;
                        buffer = new byte[strm.Length];
                        strm.Read(buffer, 0, (Int32)strm.Length);
                        buffer = Orvid.Compression.LZMACoder.Compress(buffer);
                        final.WriteByte(255);
                        final.Write(buffer, 0, buffer.Length);
                        final.Flush();
                        final.Close();
                        final.Dispose();
                    }

                    strm.Flush();
                    strm.Close();
                    strm.Dispose();
                    if (CompressionMode == CompressionType.LZMA)
                    {
                        File.Delete(OutputFileName + ".uncmpr");
                    }
                    //pictureBox1.Image = null;

                    MessageBox.Show("Conversion Completed Successfully!");
                }
                else
                {
                    throw new Exception("Unable to load the glyph typeface!");
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="Typeface"/>.
 /// </summary>
 /// <param name="Typeface"></param>
 public Typeface(System.Windows.Media.Typeface Typeface)
 {
     _typeface = Typeface;
 }
Exemplo n.º 22
0
        // todo: use this renderer; it's much better for monochrome fonts. for color there's still no better solution i know of.
        //// https://stackoverflow.com/questions/9080231/how-to-save-geometry-as-image
        //public static GenerateEmojiBitmapResults GenerateFontMap2(string fontName, int WidthAndHeight, string outputFileName)
        //{
        //  GlyphTypeface font;
        //  if (File.Exists(fontName))
        //  {
        //    font = new GlyphTypeface(new Uri(fontName));
        //  }
        //  else
        //  {
        //    Typeface face = new Typeface(fontName);
        //    face.TryGetGlyphTypeface(out font);
        //  }

        //  //int ColumnCount = 10;
        //  //int MaxDrawCount = 30; // use int.MaxValue to draw them all
        //  double fontSize = WidthAndHeight;
        //  // the height of each cell has to include over/underhanging glyphs
        //  SizeF cellSize = new SizeF((float)fontSize, (float)(fontSize * font.Height));

        //  var Glyphs = from glyphIndex in font.CharacterToGlyphMap.Values
        //               select font.GetGlyphOutline(glyphIndex, fontSize, 1d);

        //  int ColumnCount = (int)Math.Ceiling(Math.Sqrt(Glyphs.Count()));

        //  // now create the visual we'll draw them to
        //  DrawingVisual viz = new DrawingVisual();
        //  //int drawCount = -1;
        //  using (DrawingContext dc = viz.RenderOpen())
        //  {
        //    foreach (var g in Glyphs)
        //    {
        //      drawCount++;
        //      if (g.IsEmpty()) continue; // don't draw the blank ones
        //                                 // center horizontally in the cell
        //      double xOffset = (drawCount % ColumnCount) * cellSize.Width + cellSize.Width / 2d - g.Bounds.Width / 2d;
        //      // place the character on the baseline of the cell
        //      double yOffset = (drawCount / ColumnCount) * cellSize.Height + fontSize * font.Baseline;
        //      dc.PushTransform(new TranslateTransform(xOffset, yOffset));
        //      dc.DrawGeometry(System.Windows.Media.Brushes.Red, null, g);
        //      dc.Pop(); // get rid of the transform
        //    }
        //  }

        //  int RowCount = drawCount / ColumnCount;
        //  if (drawCount % ColumnCount != 0)
        //    RowCount++; // to include partial rows
        //  int bitWidth = (int)Math.Ceiling((double)(cellSize.Width * ColumnCount));
        //  int bitHeight = (int)Math.Ceiling((double)(cellSize.Height * RowCount));
        //  RenderTargetBitmap bmp = new RenderTargetBitmap(
        //                                                  bitWidth, bitHeight,
        //                                                  96, 96,
        //                                                  PixelFormats.Pbgra32);
        //  bmp.Render(viz);

        //  PngBitmapEncoder encoder = new PngBitmapEncoder();
        //  encoder.Frames.Add(BitmapFrame.Create(bmp));
        //  using (FileStream file = new FileStream(outputFileName, FileMode.Create))
        //    encoder.Save(file);
        //}



        public static GenerateEmojiBitmapResults GenerateEmojiBitmap(string fontName, int cellWidth, int cellHeight,
                                                                     float additionalScale, int shiftX, int shiftY, IEnumerable <EmojiInfo> codepointsToInclude,
                                                                     System.Drawing.Color[] backgroundPalette, System.Drawing.Color[] textPalette, float?aspectToleranceFromTarget, bool tryToFit,
                                                                     System.Windows.FontStyle fontStyle, System.Windows.FontWeight fontWeight, System.Windows.FontStretch fontStretch,
                                                                     bool strictGlyphChecking, d2.TextAntialiasMode aaMode)
        {
            System.Windows.Media.FontFamily fm = new System.Windows.Media.FontFamily(fontName);
            System.Windows.Media.Typeface   tf = new System.Windows.Media.Typeface(fm, fontStyle, fontWeight, fontStretch);
            PetsciiMapgen.ProgressReporter  pr = new PetsciiMapgen.ProgressReporter((ulong)codepointsToInclude.Count() * (ulong)backgroundPalette.Length * (ulong)textPalette.Length);
            if (!tf.TryGetGlyphTypeface(out System.Windows.Media.GlyphTypeface gtf))
            {
                PetsciiMapgen.Log.WriteLine("!!!!!!!!!! FONT FAMILY HAS NO GLYPH MAP; you will end up with unsupported glyphs in the map.");
                // throw new Exception();
            }

            // select codepoints to actually use
            PetsciiMapgen.Utils.ValueRangeInspector rangeX          = new PetsciiMapgen.Utils.ValueRangeInspector();
            PetsciiMapgen.Utils.ValueRangeInspector rangeY          = new PetsciiMapgen.Utils.ValueRangeInspector();
            PetsciiMapgen.Utils.ValueRangeInspector allAspects      = new PetsciiMapgen.Utils.ValueRangeInspector();
            PetsciiMapgen.Utils.ValueRangeInspector selectedAspects = new PetsciiMapgen.Utils.ValueRangeInspector();
            int rejectedBecauseNotInTypeface = 0;
            int rejectedBecauseAspect        = 0;

            int   targetWidth  = cellWidth;
            int   targetHeight = cellHeight;
            float targetAspect = (float)targetWidth / targetHeight;

            EmojiTest.Direct2DText dt = new EmojiTest.Direct2DText();
            dt.SetFont(fontName, targetHeight);

            var emoji = codepointsToInclude.Select(e =>
            {
                pr.Visit();
                GlyphData ret = new GlyphData();
                ret.info      = e;
                //ret.str = char.ConvertFromUtf32(cp);
                var sz     = dt.GetTextSize(ret.info.str);
                ret.width  = sz.Width;
                ret.height = sz.Height;
                rangeX.Visit(ret.width);
                rangeY.Visit(ret.height);
                allAspects.Visit(ret.width / ret.height);
                ret.scaleNeeded = 1;
                if (tryToFit)
                {
                    if (ret.height > 0 && ret.width > 0)
                    {
                        float scaleNeededY = (float)targetHeight / ret.height;// factor to match target
                        float scaleNeededX = (float)targetWidth / ret.width;
                        ret.scaleNeeded    = Math.Min(scaleNeededX, scaleNeededY);
                    }
                    else
                    {
                        ret.scaleNeeded = -1;
                    }
                }
                return(ret);
            })
                        .Where(o =>
            {
                if (o.info.forceInclude)
                {
                    return(true);
                }
                if (o.info.str == "\r" || o.info.str == "\n")
                {
                    return(false);
                }
                if (gtf != null)
                {
                    if (!gtf.CharacterToGlyphMap.ContainsKey(o.info.cps[0]))
                    {
                        rejectedBecauseNotInTypeface++;
                        if (strictGlyphChecking)
                        {
                            return(false);
                        }
                    }
                }
                float aspect = o.width / o.height;
                float da     = Math.Abs(aspect - targetAspect);
                if (aspectToleranceFromTarget.HasValue && da > aspectToleranceFromTarget)
                {
                    rejectedBecauseAspect++;
                    return(false);
                }

                selectedAspects.Visit(aspect);
                return(true);
            })
                        .OrderBy(o => o.scaleNeeded).ToArray();

            PetsciiMapgen.Log.WriteLine("EMOJI font encountered aspect ratios between {0}", allAspects);
            PetsciiMapgen.Log.WriteLine("Chars rejected because they don't have glyphs in this typeface: {0:N0}", rejectedBecauseNotInTypeface);
            PetsciiMapgen.Log.WriteLine("Chars rejected because aspect ratio out of range: {0:N0}", rejectedBecauseAspect);
            if (aspectToleranceFromTarget.HasValue)
            {
                PetsciiMapgen.Log.WriteLine("EMOJI font allowed aspect ratios between {0}", selectedAspects);
            }

            int totalCharCount = emoji.Count() * backgroundPalette.Length * textPalette.Length;
            int scaleChanges   = 0;

            int columns   = (int)Math.Ceiling(Math.Sqrt(totalCharCount));
            int rows      = columns;// we're aiming for square bitmap.
            int imgWidth  = columns * targetWidth;
            int imgHeight = rows * targetHeight;

            List <GlyphData> fullEmoji = new List <GlyphData>(totalCharCount);

            if (emoji.Length < 2)
            {
                throw new Exception("NOt enough glyphs to generate anything meaningful.");
            }

            foreach (var backgroundColor in backgroundPalette)
            {
                foreach (var textColor in textPalette)
                {
                    var bmp = new System.Drawing.Bitmap(imgWidth, imgHeight);
                    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
                    {
                        float lastScale = 0;
                        //int iemoji = 0;
                        var pr2 = new PetsciiMapgen.ProgressReporter((ulong)emoji.Count());
                        //foreach (var e in emoji)
                        for (int iemoji = 0; iemoji < emoji.Length; ++iemoji)
                        {
                            var e = emoji[iemoji];
                            pr2.Visit();
                            if (e.scaleNeeded <= 0)
                            {
                                continue;
                            }
                            if (Math.Abs(lastScale - e.scaleNeeded) > 0.001)
                            {
                                scaleChanges++;
                                dt.SetFont(fontName, targetHeight * e.scaleNeeded * additionalScale);
                            }

                            //SharpDX.Size2F sz;
                            var n = new GlyphData(e);
                            fullEmoji.Add(n);

                            RawColor4 bg = new RawColor4(backgroundColor.R / 255.0f, backgroundColor.G / 255.0f, backgroundColor.B / 255.0f, 1);
                            dt.SetColor(textColor);
                            n.bmp = dt.TextToBitmap(n.info.str, out n.bmpSize, bg, aaMode);

                            // offset where to blit from, so it's centered.
                            int ox = (int)((n.bmpSize.Width - targetWidth) / 2);
                            int oy = (int)((n.bmpSize.Height - targetHeight) / 2);
                            n.blitSourcRect = new System.Drawing.Rectangle(ox - shiftX, oy - shiftY, targetWidth, targetHeight);
                            n.bgColor       = backgroundColor;
                            n.textColor     = textColor;

                            //int y = iemoji / columns;
                            //int x = iemoji % columns;
                            //g.DrawImage(bmpChar,
                            //  new System.Drawing.Rectangle(x * targetWidth, y * targetHeight, targetWidth, targetHeight),
                            //  new System.Drawing.Rectangle(ox - shiftX, oy - shiftY, targetWidth, targetHeight), System.Drawing.GraphicsUnit.Pixel
                            //  );

                            //bmpChar.Dispose();
                            //iemoji++;
                        }
                    }
                }
            }

            PetsciiMapgen.Log.WriteLine("Scale changes: {0}", scaleChanges);
            PetsciiMapgen.Log.WriteLine("Total char count: {0}", fullEmoji.Count);
            PetsciiMapgen.Log.WriteLine("Image size to hold entire colored charset: {0}, {1}", imgWidth, imgHeight);

            GenerateEmojiBitmapResults rv = new GenerateEmojiBitmapResults();

            //rv.bmp = bmp;
            rv.columns  = columns;
            rv.rows     = rows;
            rv.AllCells = fullEmoji.ToArray();
            return(rv);
        }
Exemplo n.º 23
0
        private void ConvertButton_Click(object sender, EventArgs e)
        {
            if (OutputFileName == null || OutputFileName == "")
            {
                MessageBox.Show("Invalid File Name!");
            }
            else
            {
                //FileStream str;
                FileStream final;
                dynamic    strm;

                #region Already Exists
                if (File.Exists(OutputFileName))
                {
                    if (MessageBox.Show("A file at '" + OutputFileName + "' already exists! Would you like to overwrite it?", "File Already Exists", MessageBoxButtons.YesNoCancel) == System.Windows.Forms.DialogResult.Yes)
                    {
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    File.Create(OutputFileName).Close();
                }
                #endregion

                #region Compression Config
                //if (CompressionMode == CompressionType.Deflate)
                //{
                //    str = new FileStream(OutputFileName, FileMode.Truncate);
                //    strm = new DeflateStream(str, System.IO.Compression.CompressionMode.Compress);
                //    final = null;
                //}
                //else if (CompressionMode == CompressionType.GZip)
                //{
                //    str = new FileStream(OutputFileName, FileMode.Truncate);
                //    strm = new GZipStream(str, System.IO.Compression.CompressionMode.Compress);
                //    final = null;
                //}
                if (CompressionMode == CompressionType.LZMA)
                {
                    if (File.Exists(OutputFileName + ".uncmpr"))
                    {
                        File.Delete(OutputFileName + ".uncmpr");
                    }
                    strm  = File.Create(OutputFileName + ".uncmpr");
                    final = new FileStream(OutputFileName, FileMode.Truncate);
                }
                else
                {
                    strm  = new FileStream(OutputFileName, FileMode.Truncate);
                    final = null;
                }
                #endregion

                BinaryWriter br = new BinaryWriter(strm);

                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0); // Write the 8 empty bytes of the header
                br.Write((byte)0);
                br.Write((byte)0);
                br.Write((byte)0);

                byte[] buffer;
                br.Write((UInt16)47); // write the format version.


                string FontName = (string)FontComboBox.SelectedItem;

                buffer = ASCIIEncoding.ASCII.GetBytes(FontName);
                int i = 256 - buffer.Length;
                if (i < 0)
                {
                    throw new Exception("Font Name is to long!");
                }
                else
                {
                    br.Write(buffer);
                    for (int i2 = 0; i2 < i; i2++)
                    {
                        br.Write((byte)0); // Fill the rest of the 256 bytes.
                    }
                }

                System.Windows.Media.Typeface      t = new System.Windows.Media.Typeface(FontName);
                System.Windows.Media.GlyphTypeface glyph;
                if (t.TryGetGlyphTypeface(out glyph))
                {
                    t = null;
                    IDictionary <int, ushort> charKeyMap = (IDictionary <int, ushort>)glyph.CharacterToGlyphMap;
                    glyph = null;
                    SortedSet <int> chars = new SortedSet <int>();
                    foreach (KeyValuePair <int, ushort> c in charKeyMap)
                    {
                        chars.Add(c.Key);
                    }
                    charKeyMap = null;
                    Font f = new Font(FontName, 128, GraphicsUnit.Pixel);

                    UInt64 charsToWrite = (ulong)chars.Count; // *16;
                    br.Write(charsToWrite);                   // Write the number of chars to read.

                    int prevChar = 0;

                    for (byte style = 0; style < 1; style++)
                    {
                        f = new Font(FontName, 64, (FontStyle)style, GraphicsUnit.Pixel);
                        foreach (int ch in chars)
                        {
                            Bitmap   Backend = new Bitmap(1, 1);
                            Graphics g       = Graphics.FromImage(Backend);
                            SizeF    sz      = g.MeasureString(new String(new char[] { (char)ch }), f);
                            byte     height  = (byte)Math.Ceiling(sz.Height + 2);
                            byte     width   = (byte)Math.Ceiling(sz.Width + 4);
                            Backend = new Bitmap(width, height);
                            g       = Graphics.FromImage(Backend);
                            g.Clear(Color.White);

                            g.DrawString(new String(new char[] { (char)ch }), f, new SolidBrush(Color.Black), 2, 2);
                            g.Flush(System.Drawing.Drawing2D.FlushIntention.Flush);
                            if (prevChar + 1 == ch)
                            {
                                br.Write((byte)255); // write that it's incremented from the previous char.
                            }
                            else
                            {
                                br.Write((byte)0);    // write that it's not incremented from the previous char.
                                br.Write((UInt32)ch); // Write the char number.
                            }
                            pictureBox1.Image = Backend;
                            pictureBox1.Refresh();

                            br.Write((byte)style);  // write it's style
                            br.Write((byte)height); // write the height
                            br.Write((byte)width);  // write the width
                            buffer = ConvertToByteArray(Backend);
                            br.Write(buffer);
                            prevChar = ch;
                        }
                        strm.Flush();
                        System.GC.Collect();
                    }

                    if (CompressionMode == CompressionType.LZMA)
                    {
                        strm.Position = 0;
                        buffer        = new byte[strm.Length];
                        strm.Read(buffer, 0, (Int32)strm.Length);
                        buffer = Orvid.Compression.LZMACoder.Compress(buffer);
                        final.WriteByte(255);
                        final.Write(buffer, 0, buffer.Length);
                        final.Flush();
                        final.Close();
                        final.Dispose();
                    }

                    strm.Flush();
                    strm.Close();
                    strm.Dispose();
                    if (CompressionMode == CompressionType.LZMA)
                    {
                        File.Delete(OutputFileName + ".uncmpr");
                    }
                    //pictureBox1.Image = null;

                    MessageBox.Show("Conversion Completed Successfully!");
                }
                else
                {
                    throw new Exception("Unable to load the glyph typeface!");
                }
            }
        }
Exemplo n.º 24
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (imageViewerControl != null)
            {
                imageViewerControl.Disconnect();
                imageViewerControl.Close();
                imageViewerControl.Dispose();
                imageViewerControl = null;
            }

            ItemPickerForm picker = new ItemPickerForm();

            picker.KindFilter = Kind.Camera;
            picker.Init(Configuration.Instance.GetItems());

            if (picker.ShowDialog() == DialogResult.OK)
            {
                selectedItem = picker.SelectedItem;
                _item        = picker.SelectedItem;
                label2.Text  = selectedItem.Name;

                if (_item != null && _path != null)
                {
                    buttonExport.Enabled = true;
                }

                try
                {
                    imageViewerControl      = ClientControl.Instance.GenerateImageViewerControl();
                    imageViewerControl.Dock = DockStyle.Fill;
                    panel1.Controls.Clear();
                    panel1.Controls.Add(imageViewerControl);
                    imageViewerControl.CameraFQID        = selectedItem.FQID;
                    imageViewerControl.EnableDigitalZoom = true;

                    imageViewerControl.EnableVisibleHeader = false;

                    imageViewerControl.Initialize();
                    imageViewerControl.Connect();

                    //add overlay text on top of video
                    var fontFamily = new System.Windows.Media.FontFamily("Open Sans Semibold");
                    var typeface   = new System.Windows.Media.Typeface(fontFamily, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Bold, new System.Windows.FontStretch());
                    var fText      = new System.Windows.Media.FormattedText(selectedItem.Name, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, 25, System.Windows.Media.Brushes.White);
                    var path       = new System.Windows.Shapes.Path()
                    {
                        Data = fText.BuildGeometry(new System.Windows.Point(20, 160)), Fill = System.Windows.Media.Brushes.White
                    };
                    var id = imageViewerControl.ShapesOverlayAdd(new List <System.Windows.Shapes.Shape> {
                        path
                    }, new ShapesOverlayRenderParameters()
                    {
                        ZOrder = 100
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception " + ex);
                }
            }
        }