Exemple #1
0
        public static PageElement NewText(string text, int x, int y, uint color, FontType font, string uid)
        {
            PageElement pe = NewText(text, x, y, color, font);

            pe.set_uid_for_preview(uid);
            return(pe);
        }
Exemple #2
0
 public static string IdFor(FontType font)
 {
     return(font switch
     {
         FontType.Delta => Items.FontDelta,
         _ => null
     });
Exemple #3
0
        internal async Task SelectFontAsyncInternal(FontType fontType)
        {
            Command c = new Command(CommandType.DirectNoReply);

            c.SelectFont(fontType);
            await _brick.SendCommandAsyncInternal(c);
        }
Exemple #4
0
		public Rectangle this[FontType type]
		{
			get
			{
				return m_BiggestCharSize[(int)type]; 
			}
		}
Exemple #5
0
        /// <summary>
        /// Append the Select Font command to an existing Command object
        /// </summary>
        /// <param name="c">The command.</param>
        /// <param name="fontType">The font to select</param>
        /// <returns>The updated command.</returns>
        public static Command SelectFont(this Command c, FontType fontType)
        {
            c.AddOpcode(Opcode.UIDraw_SelectFont);
            c.AddParameter((byte)fontType);

            return(c);
        }
Exemple #6
0
   //------------------------------------------------------------------------------------------xx.03.2006
   /// <summary>Gets a font definition for the specified standard font.</summary>
   /// <param name="report">Report to which this font belongs</param>
   /// <param name="standardFont">Standard font enumeration value</param>
   /// <returns>Font definition for the specified standard font</returns>
   /// <remarks>
   /// If the font is already registered, the handle of the registered font definition will be returned.
   /// </remarks>
   private static FontDef fontDef_Check(Report report, String sFontName, FontType fontType)
   {
       if (sFontName == null)
       {
           throw new ArgumentNullException("sFontName", "font name must be specified");
       }
 #if Framework2
       FontDef fontDef;
       if (report.dict_FontDef.TryGetValue(sFontName, out fontDef))
       {
           if (fontDef.fontType != fontType)
           {
               throw new ReportException(String.Format("Font '{0}' has been defined as '{1}' font.", sFontName, fontDef.fontType.ToString("G")));
           }
           return(fontDef);
       }
 #else
       FontDef fontDef = (FontDef)report.dict_FontDef[sFontName];
       if (fontDef != null)
       {
           if (fontDef.fontType != fontType)
           {
               throw new ReportException(String.Format("Font '{0}' has been defined as '{1}' font.", sFontName, fontDef.fontType.ToString("G")));
           }
           return(fontDef);
       }
 #endif
       return(null);
   }
Exemple #7
0
        private bool LoadFontData(string fontFileName)
        {
            Fonts = new FontType[95];

            try
            {
                fontFileName = SystemConfiguration.FontFilePath + fontFileName;

                var fontDataLines = File.ReadAllLines(fontFileName);

                var index = 0;

                foreach (var line in fontDataLines)
                {
                    var modelArray = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    Fonts[index++] = new FontType()
                    {
                        left  = float.Parse(modelArray[modelArray.Length - 3]),
                        right = float.Parse(modelArray[modelArray.Length - 2]),
                        size  = int.Parse(modelArray[modelArray.Length - 1]),
                    };
                }

                fontDataLines = null;

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        // <summary>
        /// Set maxFontSize for accessibility - large text
        /// </summary>
        /// <param name="label"></param>
        /// <param name="fontType"></param>
        /// <param name="rawText"></param>
        /// <param name="lineHeight"></param>
        /// <param name="fontSize"></param>
        /// <param name="maxFontSize"></param>
        /// <param name="alignment"></param>
        public static void InitUITextViewWithSpacingAndUrl(UITextView label, FontType fontType, string rawText, double lineHeight, float fontSize, float maxFontSize, UITextAlignment alignment = UITextAlignment.Left)
        {
            //Defining attibutes inorder to format the embedded link
            NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML
            };

            documentAttributes.StringEncoding = NSStringEncoding.UTF8;
            NSError            error            = null;
            NSAttributedString attributedString = new NSAttributedString(NSData.FromString(rawText, NSStringEncoding.UTF8), documentAttributes, ref error);

            NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();

            paragraphStyle.LineHeightMultiple = new nfloat(lineHeight);
            paragraphStyle.Alignment          = alignment;
            NSMutableAttributedString text = new NSMutableAttributedString(attributedString);
            NSRange range = new NSRange(0, text.Length);

            text.AddAttribute(UIStringAttributeKey.ParagraphStyle, paragraphStyle, range);
            text.AddAttribute(UIStringAttributeKey.Font, Font(fontType, fontSize, maxFontSize), range);
            label.AttributedText = text;

            label.TextColor = UIColor.White;
            label.WeakLinkTextAttributes = new NSDictionary(UIStringAttributeKey.ForegroundColor, "#FADC5D".ToUIColor(), UIStringAttributeKey.UnderlineStyle, new NSNumber(1));
        }
Exemple #9
0
        public FontSetup(FontInfo fontInfo, FontType proxyFontType) {
            this.fontInfo = fontInfo;

            // Add the base 14 fonts
            AddBase14Fonts();
            AddSystemFonts(proxyFontType);
        }
        public CommonSize MeasureStringSize(object graphics, FontType font, string text)
        {
            var isGdi = graphics is Graphics;

            var sizeCache = (isGdi ? gdiSizeCaches : dwSizeCaches).GetOrAdd(font, f =>
            {
                int lineHeight;

                if (isGdi)
                {
                    lineHeight = TextRenderer.MeasureText((Graphics)graphics, "X", Fonts.GetFont(font), Size.Empty, App.DefaultTextFormatFlags).Height;
                }
                else
                {
                    using (var layout = new SharpDX.DirectWrite.TextLayout(Fonts.Factory, "X", Fonts.GetTextFormat(font), 1000000, 1000000))
                    {
                        var metrics = layout.Metrics;
                        lineHeight  = (int)metrics.Height;
                        //lineHeight = (int)Math.Ceiling(Fonts.GetTextFormat(font).FontSize);
                    }
                }

                return(Tuple.Create(new ConcurrentDictionary <string, CommonSize>(), new ConcurrentStack <string>(), lineHeight));
            });

            return(sizeCache.Item1.GetOrAdd(text, s =>
            {
                if (sizeCache.Item2.Count >= sizeCacheStackLimit)
                {
                    string value;
                    if (sizeCache.Item2.TryPop(out value))
                    {
                        CommonSize _s;
                        sizeCache.Item1.TryRemove(value, out _s);
                    }
                }

                sizeCache.Item2.Push(s);

                if (isGdi)
                {
                    var size = TextRenderer.MeasureText((IDeviceContext)graphics, text, Fonts.GetFont(font), Size.Empty, App.DefaultTextFormatFlags);
                    return new CommonSize(size.Width, sizeCache.Item3);
                }
                else
                {
                    try
                    {
                        using (var layout = new SharpDX.DirectWrite.TextLayout(Fonts.Factory, text, Fonts.GetTextFormat(font), 1000000, 1000000))
                        {
                            var metrics = layout.Metrics;

                            return new CommonSize((int)metrics.WidthIncludingTrailingWhitespace, sizeCache.Item3);
                        }
                    }
                    catch { }
                    return new CommonSize(100, 10);
                }
            }));
        }
Exemple #11
0
        public void AddText(Vector2 position, Color color, FontType type, string text)
        {
            var list = GetList();

            switch (type)
            {
            case FontType.Normal:
                list.AddText(position, color.ToImGuiColor(), text);
                break;

            case FontType.Bold:
                ImGui.PushFont(_controller.BoldFont);
                list.AddText(position, color.ToImGuiColor(), text);
                ImGui.PopFont();
                break;

            case FontType.Large:
                ImGui.PushFont(_controller.LargeFont);
                list.AddText(position, color.ToImGuiColor(), text);
                ImGui.PopFont();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
 public ThemeFontSettingsImpl(string name, FontType fontType, DefaultFontInfo defaultFontInfo)
 {
     Name                 = name ?? throw new ArgumentNullException(nameof(name));
     FontType             = fontType;
     toSettings           = new Dictionary <Guid, FontSettingsImpl>();
     this.defaultFontInfo = defaultFontInfo;
 }
Exemple #13
0
 /// <summary>
 /// Private constructor.
 /// </summary>
 /// <param name="type">the type</param>
 /// <param name="size">the font size</param>
 /// <param name="color">the color</param>
 /// <param name="style">the style</param>
 private TextInfo(FontType type, float size, Color color, FontStyle style)
 {
     Type  = type;
     Size  = size;
     Color = color;
     Style = style;
 }
Exemple #14
0
    protected override void OnEnable()
    {
        base.OnEnable();
        SerializedProperty bit = serializedObject.FindProperty("mFont");

        mFontType = (bit != null && bit.objectReferenceValue != null) ? FontType.NGUI : FontType.Unity;
    }
 public void ChangeFont(FontType fontType)
 {
     TextEquation.FontType = fontType;
     ActiveChild.FontSize = FontSize;
     CalculateSize();
     AdjustCarets();
 }
Exemple #16
0
 /// <inheritdoc cref="ICanvas"/>
 public ICanvas SetFont(FontType fontType, FontStyle fontStyle, float fontSize)
 {
     currentFontType  = fontType;
     currentFontStyle = fontStyle;
     currentFontSize  = ValidationUtil.RequirePositive(fontSize, $"fontSize({fontSize}) has to be positive.");
     return(this);
 }
Exemple #17
0
        public static PageElement NewUid(int x, int y, uint color, FontType font)
        {
            PageElement temp = new PageElement("", x, y, color, font);

            temp.type = ElementType.UID;
            return(temp);
        }
Exemple #18
0
    protected override void OnEnable()
    {
        base.OnEnable();
        SerializedProperty bit = serializedObject.FindProperty("mFont");

        mType = (bit != null && bit.objectReferenceValue != null) ? FontType.Bitmap : FontType.Dynamic;
    }
        void DetermineFontType()
        {
            FontType fontType = FontType.STIXSizeOneSym;

            switch (Symbol)
            {
            case SignCompositeSymbol.Integral:
            case SignCompositeSymbol.DoubleIntegral:
            case SignCompositeSymbol.TripleIntegral:
            case SignCompositeSymbol.ContourIntegral:
            case SignCompositeSymbol.SurfaceIntegral:
            case SignCompositeSymbol.VolumeIntegral:
            case SignCompositeSymbol.ClockContourIntegral:
            case SignCompositeSymbol.AntiClockContourIntegral:
                if (UseItalicIntegralSign)
                {
                    fontType = FontType.STIXGeneral;
                }
                else
                {
                    fontType = FontType.STIXIntegralsUp;
                }
                break;

            case SignCompositeSymbol.Intersection:
            case SignCompositeSymbol.Union:
                fontType = FontType.STIXGeneral;
                break;
            }
            FontType = fontType;
        }
Exemple #20
0
        public new static void Parse(XNode node, DefinitionFile file)
        {
            UiView.Parse(node, file);

            var parser = new DefinitionParser(node);

            file["Processor"] = Type.GetType(node.Attribute("Processor"));

            file["LinkResolver"] = parser.ParseDelegate("LinkResolver");

            file["ImageNotLoaded"] = parser.ParseResource <Texture2D>("ImageNotLoaded");

            file["EnableBaseLineCorrection"] = parser.ParseBoolean("EnableBaseLineCorrection");

            file["Text"]        = parser.ParseString("Text");
            file["Font"]        = parser.ValueOrNull("Font");
            file["FontSize"]    = parser.ParseInt("FontSize");
            file["FontSpacing"] = parser.ParseInt("FontSpacing");

            for (int idx = 0; idx < (int)FontType.Count; ++idx)
            {
                FontType type    = (FontType)idx;
                string   font    = string.Format("{0}.Font", type);
                string   spacing = string.Format("{0}.FontSpacing", type);
                string   resize  = string.Format("{0}.FontResize", type);

                file[font]    = parser.ValueOrNull(font);
                file[spacing] = parser.ParseInt(spacing);
                file[resize]  = parser.ParseInt(resize);
            }

            for (int idx = 0; idx < (int)SizeType.Count; ++idx)
            {
                SizeType type = (SizeType)idx;
                string   size = string.Format("{0}.FontSize", type);

                file[size] = parser.ParseInt(size);
            }

            file["LineHeight"]       = parser.ParseInt("LineHeight");
            file["Indent"]           = parser.ParseLength("Indent");
            file["ParagraphSpacing"] = parser.ParseLength("ParagraphSpacing");

            file["Justify"] = parser.ParseBoolean("Justify");

            file["TextColor"]            = parser.ParseColor("TextColor");
            file["LinkColor"]            = parser.ParseColor("LinkColor");
            file["ActiveLinkColor"]      = parser.ParseColor("ActiveLinkColor");
            file["HorizontalRulerColor"] = parser.ParseColor("HorizontalRulerColor");

            file["HorizontalContentAlignment"] = parser.ParseEnum <HorizontalContentAlignment>("HorizontalContentAlignment");
            file["VerticalContentAlignment"]   = parser.ParseEnum <VerticalContentAlignment>("VerticalContentAlignment");

            file["BulletText"]            = parser.ParseString("BulletText");
            file["HorizontalRulerHeight"] = parser.ParseLength("HorizontalRulerHeight");

            file["ClickMargin"] = parser.ParseLength("ClickMargin");
            file["UrlClick"]    = parser.ParseDelegate("UrlClick");
        }
 protected void InitBodyText(UITextView textView, string text, FontType fontType = FontType.FontRegular)
 {
     InitTextViewWithSpacingAndHTMLFormat(textView, fontType, text, 1.28, 16, 22);
     textView.ContentInset       = UIEdgeInsets.Zero;
     textView.TextContainerInset = UIEdgeInsets.Zero;
     textView.TextContainer.LineFragmentPadding = 0;
     textView.DataDetectorTypes = UIDataDetectorType.PhoneNumber | UIDataDetectorType.Link;
 }
Exemple #22
0
        public static PageElement NewSensorPm10(int idx, int x, int y, uint color, FontType font)
        {
            PageElement temp = new PageElement("", x, y, color, font);

            temp.type = ElementType.SENSOR_PM10;
            temp.idx  = idx;
            return(temp);
        }
		public ThemeFontSettingsImpl(string name, FontType fontType, DefaultFontInfo defaultFontInfo) {
			if (name == null)
				throw new ArgumentNullException(nameof(name));
			Name = name;
			FontType = fontType;
			toSettings = new Dictionary<Guid, FontSettingsImpl>();
			this.defaultFontInfo = defaultFontInfo;
		}
Exemple #24
0
 public void AddTempate(FontType obj)
 {
     if (this.fontTemplates.ContainsKey(obj.name))
     {
         throw new UiSimuationException(string.Format("An xml element with name {0} is already loaded.", obj.name));
     }
     this.fontTemplates[obj.name] = obj;
 }
Exemple #25
0
    public static Font GetFont(FontType type)
    {
        Font font = null;

        FONTS.TryGetValue(type, out font);

        return(font);
    }
Exemple #26
0
 public void setType(FontType ftype)
 {
     OgreOverlayPINVOKE.Font_setType(swigCPtr, (int)ftype);
     if (OgreOverlayPINVOKE.SWIGPendingException.Pending)
     {
         throw OgreOverlayPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemple #27
0
        /// <summary>
        /// Set maxFontSize for accessibility - large text
        /// </summary>
        /// <param name="label"></param>
        /// <param name="fontType"></param>
        /// <param name="text"></param>
        /// <param name="fontSize"></param>
        /// <param name="maxFontSize"></param>
        public static void InitUnderlinedLabel(UILabel label, FontType fontType, string text, float fontSize, float maxFontSize)
        {
            var attributedString = new NSMutableAttributedString(text);

            attributedString.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attributedString.Length));
            label.AttributedText = attributedString;
            label.Font           = Font(fontType, fontSize, maxFontSize);
        }
        SelectFontAsync(FontType fontType)
        {
            return(SelectFontAsyncInternal(fontType)
#if WINRT
                   .AsAsyncAction()
#endif
                   );
        }
Exemple #29
0
        public FontSetup(FontInfo fontInfo, FontType proxyFontType)
        {
            this.fontInfo = fontInfo;

            // Add the base 14 fonts
            AddBase14Fonts();
            AddSystemFonts(proxyFontType);
        }
Exemple #30
0
 public void Update()
 {
     if (fontType != _dirtyFontType)
     {
         _setTextParameters(_fontManager.GetFont(fontType));
     }
     _dirtyFontType = fontType;
 }
Exemple #31
0
        public static void InitMonospacedLabel(UILabel label, FontType fontType, string rawText, double lineHeight, float fontSize, float maxFontSize, UITextAlignment alignment = UITextAlignment.Left)
        {
            NSMutableAttributedString text = new NSMutableAttributedString(rawText);
            NSRange range = new NSRange(0, rawText.Length);

            text.AddAttribute(UIStringAttributeKey.Font, Font(fontType, fontSize, maxFontSize), range);
            label.AttributedText = text;
        }
        // get opengl texture index
        internal static int GetTextureIndex(FontType FontType, int Codepoint)
        {
            int    Font = (int)FontType;
            string t    = char.ConvertFromUtf32(Codepoint);
            int    i    = char.ConvertToUtf32(t, 0);

            if (i >= Characters[Font].Length || Characters[Font][i].Texture == -1)
            {
                if (Characters[Font].Length == 0)
                {
                    Characters[Font] = new Character[i + 1];
                    for (int j = 0; j <= i; j++)
                    {
                        Characters[Font][j].Texture = -1;
                    }
                }
                while (i >= Characters[Font].Length)
                {
                    int n = Characters[Font].Length;
                    Array.Resize <Character>(ref Characters[Font], 2 * n);
                    for (int j = n; j < 2 * n; j++)
                    {
                        Characters[Font][j].Texture = -1;
                    }
                }
                float s1;
                switch (Font)
                {
                case 0: s1 = ExtraSmallFontSize; break;

                case 1: s1 = SmallFontSize; break;

                case 2: s1 = MediumFontSize; break;

                case 3: s1 = LargeFontSize; break;

                case 4: s1 = ExtraLargeFontSize; break;

                default: s1 = SmallFontSize; break;
                }
                int       s0w = Interface.RoundToPowerOfTwo((int)Math.Ceiling((double)s1 * 1.25));
                int       s0h = s0w;
                FontStyle fs  = Font == 0 ? FontStyle.Regular : FontStyle.Regular;
                Bitmap    b   = new Bitmap(s0w, s0h, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics  g   = Graphics.FromImage(b);
                g.Clear(Color.Black);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                Font  f = new Font(FontFamily.GenericSansSerif, s1, fs, GraphicsUnit.Pixel);
                SizeF s = g.MeasureString(t, f, s0w, StringFormat.GenericTypographic);
                g.DrawString(t, f, Brushes.White, 0.0f, 0.0f);
                g.Dispose();
                Characters[Font][i].Texture = TextureManager.RegisterTexture(b, false);
                Characters[Font][i].Width   = s.Width <= 0.05f ? 4.0f : (float)Math.Ceiling((double)s.Width);
                Characters[Font][i].Height  = s.Height <= 0.05f ? 4.0f : (float)Math.Ceiling((double)s.Height);
                b.Dispose();
            }
            return(Characters[Font][i].Texture);
        }
Exemple #33
0
 public PageElement(string text, int x, int y, uint color, FontType font)
 {
     this.type  = ElementType.TEXT;
     this.x     = x;
     this.y     = y;
     this.color = color;
     this.text  = text;
     this.font  = font;
 }
Exemple #34
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="name">Name</param>
 /// <param name="fontType">Font type</param>
 public ExportThemeFontSettingsDefinitionAttribute(string name, FontType fontType)
 {
     if (name == null)
     {
         throw new ArgumentNullException(nameof(name));
     }
     Name     = name;
     FontType = fontType;
 }
 public StyleType()
 {
     _protection = new ProtectionType();
     _numberFormat = new NumberFormatType();
     _interior = new InteriorType();
     _font = new FontType();
     _borders = new List<BorderType>();
     _alignment = new AlignmentType();
 }
Exemple #36
0
        /// <summary>
        /// Drawn text using given font, position and color
        /// </summary>
        public void DrawText(FontType font, String text, Vector2 position, Color color, bool dropShadow)
        {
            if (mIsTextModeActive)
            {
                if (dropShadow)
                    mSpriteBatch.DrawString(Fonts[(int)font], text, position + mDropShadowOffset, new Color(color.ToVector4() * new Vector4(0, 0, 0, 1)));

                mSpriteBatch.DrawString(Fonts[(int)font], text, position, color);
            }
        }
	void OnSelectFont (Object obj)
	{
		// Undo doesn't work correctly in this case... so I won't bother.
		//NGUIEditorTools.RegisterUndo("Font Change");
		//NGUIEditorTools.RegisterUndo("Font Change", mFont);

		mFont.replacement = obj as UIFont;
		mReplacement = mFont.replacement;
		NGUITools.SetDirty(mFont);
		if (mReplacement == null) mType = FontType.Bitmap;
	}
 public static FontFamily GetFontFamily(FontType fontType)
 {
     if (fontFamilies.Keys.Contains(fontType))
     {
         return fontFamilies[fontType];
     }
     else
     {
         return new FontFamily("Segoe UI");
     }
 }
Exemple #39
0
	void OnSelectFont (MonoBehaviour obj)
	{
		// Undo doesn't work correctly in this case... so I won't bother.
		//NGUIEditorTools.RegisterUndo("Font Change");
		//NGUIEditorTools.RegisterUndo("Font Change", mFont);

		mFont.replacement = obj as UIFont;
		mReplacement = mFont.replacement;
		UnityEditor.EditorUtility.SetDirty(mFont);
		if (mReplacement == null) mType = FontType.Normal;
	}
 public TextFormat(double size, FontType ft, FontStyle fs, FontWeight fw, SolidColorBrush brush, bool useUnderline)
 {
     this.FontSize = Math.Round(size, 1);
     this.FontType = ft;
     this.FontFamily = FontFactory.GetFontFamily(ft);
     this.FontStyle = fs;
     this.UseUnderline = useUnderline;
     this.FontWeight = fw;
     this.TextBrush = brush;
     this.TypeFace = new Typeface(FontFamily, fs, fw, FontStretches.Normal, FontFactory.GetFontFamily(FontType.STIXGeneral));
     BrushConverter bc = new BrushConverter();
     TextBrushString = bc.ConvertToString(brush);
 }
Exemple #41
0
        public static List<LoactedPic> GetFontPicList(string value, FontType fontType)
        {
            List<LoactedPic> result = null;
            List<ImageWithName> source = null;

            if (fontType == FontType.Lv)
                source = Cache.Get("ListLv") as List<ImageWithName>;
            if (fontType == FontType.HP || fontType == FontType.ATK)
                source = Cache.Get("ListNormal") as List<ImageWithName>;
            if (source == null)
                return result;

            result = new List<LoactedPic>();
            foreach (char c in value)
            {
                Image word = source.Find(item => item.Name == c.ToString()).Img;
                LoactedPic lp = new LoactedPic(word);
                result.Add(lp);
            }

            int firstX = 0, topY = 0;
            switch (fontType)
            {
                case FontType.Lv:
                    firstX = 72 - result.Sum(item => item.Img.Width) / 2;
                    topY = 825;
                    break;
                case FontType.HP:
                    firstX = 610 - result.Sum(item => item.Img.Width);
                    topY = 781;
                    break;
                case FontType.ATK:
                    firstX = 390 - result.Sum(item => item.Img.Width);
                    topY = 838;
                    break;
            }

            int startX;
            for (int i = 0; i < result.Count; i++)
            {
                if (i > 0)
                    startX = result[i - 1].EndX + 1;
                else
                    startX = firstX;
                result[i].StartX = startX;
                result[i].StartY = topY;
            }

            return result;
        }
Exemple #42
0
        public SubtitleFont(FontType t, string fn)
        {
            type = t;
            fontName = fn;

            letters = new LinkedList<SubtitleLetter>();

            if (type == FontType.ProgramFont)
                fileName = Application.StartupPath + "\\" + fontName + ".font.txt";
            else
                fileName = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\SupRip\\" + fontName + ".font.txt";

            if (File.Exists(fileName))
            {
                StreamReader sr = new StreamReader(fileName);

                string text;

                // Skip past the version line
                text = sr.ReadLine();

                while ((text = sr.ReadLine()) != null)
                {
                    string[] arraySize = sr.ReadLine().Trim().Split(' ');

                    if (arraySize.Length != 2)
                        throw new FontfileFormatException("arraySize is screwed up: " + arraySize);

                    int w = Int32.Parse(arraySize[0]);
                    int h = Int32.Parse(arraySize[1]);
                    byte[,] letterArray = new byte[h, w];
                    for (int j = 0; j < h; j++)
                    {
                        string[] arrayLine = sr.ReadLine().Trim().Split(' ');
                        if (arrayLine.Length != w)
                            throw new FontfileFormatException("arrayLine is " + arrayLine.Length + " instead of " + w);

                        for (int i = 0; i < w; i++)
                            letterArray[j, i] = Byte.Parse(arrayLine[i]);
                    }

                    letters.AddLast(new SubtitleLetter(letterArray, text));

                    // Skip the empty line between letters
                    sr.ReadLine();
                }

                sr.Close();
            }
        }
Exemple #43
0
		public static SizeF MessureString(int maxLength, FontType fontType, View3D view, float scale)
		{
			float width = 0, height = 0;

			Rectangle charSize = Effect.TextFont[fontType];

			height = (float)charSize.Height;
			width = (float)charSize.Width * maxLength; 

			width *= scale;
			height *= scale;

			return new SizeF(width, height);
		}
Exemple #44
0
 // get opengl texture index
 internal static int GetTextureIndex(FontType FontType, int Codepoint)
 {
     int Font = (int)FontType;
     string t = char.ConvertFromUtf32(Codepoint);
     int i = char.ConvertToUtf32(t, 0);
     if (i >= Characters[Font].Length || Characters[Font][i].Texture == -1) {
         if (Characters[Font].Length == 0) {
             Characters[Font] = new Character[i + 1];
             for (int j = 0; j <= i; j++) {
                 Characters[Font][j].Texture = -1;
             }
         }
         while (i >= Characters[Font].Length) {
             int n = Characters[Font].Length;
             Array.Resize<Character>(ref Characters[Font], 2 * n);
             for (int j = n; j < 2 * n; j++) {
                 Characters[Font][j].Texture = -1;
             }
         }
         float s1;
         switch (Font) {
             case 0: s1 = ExtraSmallFontSize; break;
             case 1: s1 = SmallFontSize; break;
             case 2: s1 = MediumFontSize; break;
             case 3: s1 = LargeFontSize; break;
             case 4: s1 = ExtraLargeFontSize; break;
             default: s1 = SmallFontSize; break;
         }
         int s0w = Interface.RoundToPowerOfTwo((int)Math.Ceiling((double)s1 * 1.25));
         int s0h = s0w;
         FontStyle fs = Font == 0 ? FontStyle.Regular : FontStyle.Regular;
         Bitmap b = new Bitmap(s0w, s0h, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
         Graphics g = Graphics.FromImage(b);
         g.Clear(Color.Black);
         g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
         Font f = new Font(FontFamily.GenericSansSerif, s1, fs, GraphicsUnit.Pixel);
         SizeF s = g.MeasureString(t, f, s0w, StringFormat.GenericTypographic);
         g.DrawString(t, f, Brushes.White, 0.0f, 0.0f);
         g.Dispose();
         Characters[Font][i].Texture = TextureManager.RegisterTexture(b, false);
         Characters[Font][i].Width = s.Width <= 0.05f ? 4.0f : (float)Math.Ceiling((double)s.Width);
         Characters[Font][i].Height = s.Height <= 0.05f ? 4.0f : (float)Math.Ceiling((double)s.Height);
         b.Dispose();
     }
     return Characters[Font][i].Texture;
 }
Exemple #45
0
		public RectangleF this[FontType type, char @char]
		{
			get 
			{
				RectangleF rect;

				Dictionary<char, RectangleF> charLookup;

				charLookup = m_CharLookup[(int)type];
				
				if (charLookup.TryGetValue(@char, out rect))
				{
					return rect;
				}
				else
				{
					return charLookup['?'];
				}				
			}			
		}
Exemple #46
0
		public static SizeF MessureString(string str, FontType fontType, View3D view, float scale)
		{
			float width = 0, height = 0;

			foreach (char @char in str)
			{
				RectangleF rect = Effect.TextFont[fontType, @char];

				if (rect.Height > height)
				{
					height = rect.Height; 
				}

				width += rect.Width; 
			}

			width *= Effect.TextFont.TextureSize * scale;
			height *= Effect.TextFont.TextureSize * scale;

			return new SizeF(width, height);
		}
	void OnEnable ()
	{
		SerializedProperty bit = serializedObject.FindProperty("bitmapFont");
		mType = (bit.objectReferenceValue != null) ? FontType.Bitmap : FontType.Dynamic;
		mList = target as UIPopupList;

		if (mList.ambigiousFont == null)
		{
			mList.ambigiousFont = NGUISettings.ambigiousFont;
			mList.fontSize = NGUISettings.fontSize;
			mList.fontStyle = NGUISettings.fontStyle;
			EditorUtility.SetDirty(mList);
		}

		if (mList.atlas == null)
		{
			mList.atlas = NGUISettings.atlas;
			mList.backgroundSprite = NGUISettings.selectedSprite;
			mList.highlightSprite = NGUISettings.selectedSprite;
			EditorUtility.SetDirty(mList);
		}
	}
Exemple #48
0
        /// <summary>
        ///     Adds all the system fonts to the FontInfo object.
        /// </summary>
        /// <remarks>
        ///     Adds metrics for basic fonts and useful family-style-weight
        ///     triplets for lookup.
        /// </remarks>
        /// <param name="fontType">Determines what type of font to instantiate.</param>
        private void AddSystemFonts(FontType fontType) {
            GdiFontEnumerator enumerator = new GdiFontEnumerator(new GdiDeviceContent());
            foreach (string familyName in enumerator.FamilyNames) {
                if (IsBase14FontName(familyName)) {
                    FonetDriver.ActiveDriver.FireFonetWarning(
                        "Will ignore TrueType font '" + familyName + "' because a base 14 font with the same name already exists.");

                }
                else {
                    FontStyles styles = enumerator.GetStyles(familyName);

                    string name = GetNextAvailableName();
                    fontInfo.AddMetrics(name, new ProxyFont(new FontProperties(familyName, false, false), fontType));
                    fontInfo.AddFontProperties(name, familyName, "normal", "normal");

                    name = GetNextAvailableName();
                    fontInfo.AddMetrics(name, new ProxyFont(new FontProperties(familyName, true, false), fontType));
                    fontInfo.AddFontProperties(name, familyName, "normal", "bold");

                    name = GetNextAvailableName();
                    fontInfo.AddMetrics(name, new ProxyFont(new FontProperties(familyName, false, true), fontType));
                    fontInfo.AddFontProperties(name, familyName, "italic", "normal");

                    name = GetNextAvailableName();
                    fontInfo.AddMetrics(name, new ProxyFont(new FontProperties(familyName, true, true), fontType));
                    fontInfo.AddFontProperties(name, familyName, "italic", "bold");
                }
            }

            // Cursive - Monotype Corsiva
            fontInfo.AddMetrics("F15", new ProxyFont(new FontProperties("Monotype Corsiva", false, false), fontType));
            fontInfo.AddFontProperties("F15", "cursive", "normal", "normal");

            // Fantasy - Zapf Dingbats
            fontInfo.AddMetrics("F16", Base14Font.ZapfDingbats);
            fontInfo.AddFontProperties("F16", "fantasy", "normal", "normal");
        }
 public static Typeface GetTypeface(FontType fontType, FontStyle fontStyle, FontWeight fontWeight)
 {
     return new Typeface(GetFontFamily(fontType), fontStyle, fontWeight, FontStretches.Normal, GetFontFamily(FontType.STIXGeneral));
 }
	void DrawFont ()
	{
		if (NGUIEditorTools.DrawHeader("Font"))
		{
			NGUIEditorTools.BeginContents();

			SerializedProperty ttf = null;

			GUILayout.BeginHorizontal();
			{
				if (NGUIEditorTools.DrawPrefixButton("Font"))
				{
					if (mType == FontType.Bitmap)
					{
						ComponentSelector.Show<UIFont>(OnBitmapFont);
					}
					else
					{
						ComponentSelector.Show<Font>(OnDynamicFont, new string[] { ".ttf", ".otf"});
					}
				}

#if DYNAMIC_FONT
				GUI.changed = false;
				mType = (FontType)EditorGUILayout.EnumPopup(mType, GUILayout.Width(62f));

				if (GUI.changed)
				{
					GUI.changed = false;

					if (mType == FontType.Bitmap)
					{
						serializedObject.FindProperty("trueTypeFont").objectReferenceValue = null;
					}
					else
					{
						serializedObject.FindProperty("bitmapFont").objectReferenceValue = null;
					}
				}
#else
				mType = FontType.Bitmap;
#endif

				if (mType == FontType.Bitmap)
				{
					NGUIEditorTools.DrawProperty("", serializedObject, "bitmapFont", GUILayout.MinWidth(40f));
				}
				else
				{
					ttf = NGUIEditorTools.DrawProperty("", serializedObject, "trueTypeFont", GUILayout.MinWidth(40f));
				}
			}
			GUILayout.EndHorizontal();

			if (ttf != null && ttf.objectReferenceValue != null)
			{
				GUILayout.BeginHorizontal();
				{
					EditorGUI.BeginDisabledGroup(ttf.hasMultipleDifferentValues);
					NGUIEditorTools.DrawProperty("Font Size", serializedObject, "fontSize", GUILayout.Width(142f));
					NGUIEditorTools.DrawProperty("", serializedObject, "fontStyle", GUILayout.MinWidth(40f));
					NGUIEditorTools.DrawPadding();
					EditorGUI.EndDisabledGroup();
				}
				GUILayout.EndHorizontal();
			}
			else NGUIEditorTools.DrawProperty("Font Size", serializedObject, "fontSize", GUILayout.Width(142f));

			NGUIEditorTools.DrawProperty("Text Color", serializedObject, "textColor");

			GUILayout.BeginHorizontal();
			NGUIEditorTools.SetLabelWidth(66f);
			EditorGUILayout.PrefixLabel("Padding");
			NGUIEditorTools.SetLabelWidth(14f);
			NGUIEditorTools.DrawProperty("X", serializedObject, "padding.x", GUILayout.MinWidth(30f));
			NGUIEditorTools.DrawProperty("Y", serializedObject, "padding.y", GUILayout.MinWidth(30f));
			NGUIEditorTools.DrawPadding();
			NGUIEditorTools.SetLabelWidth(80f);
			GUILayout.EndHorizontal();

			NGUIEditorTools.EndContents();
		}
	}
	/// <summary>
	/// Draw the label's properties.
	/// </summary>

	protected override bool ShouldDrawProperties ()
	{
		mLabel = mWidget as UILabel;

		GUILayout.BeginHorizontal();
		
		if (NGUIEditorTools.DrawPrefixButton("Font"))
		{
			if (mFontType == FontType.NGUI)
			{
				ComponentSelector.Show<UIFont>(OnNGUIFont);
			}
			else
			{
				ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
			}
		}

#if DYNAMIC_FONT
		mFontType = (FontType)EditorGUILayout.EnumPopup(mFontType, GUILayout.Width(62f));
#else
		mFontType = FontType.NGUI;
#endif
		bool isValid = false;
		SerializedProperty fnt = null;
		SerializedProperty ttf = null;

		if (mFontType == FontType.NGUI)
		{
			fnt = NGUIEditorTools.DrawProperty("", serializedObject, "mFont", GUILayout.MinWidth(40f));
			
			if (fnt.objectReferenceValue != null)
			{
				NGUISettings.ambigiousFont = fnt.objectReferenceValue;
				isValid = true;
			}
		}
		else
		{
			ttf = NGUIEditorTools.DrawProperty("", serializedObject, "mTrueTypeFont", GUILayout.MinWidth(40f));

			if (ttf.objectReferenceValue != null)
			{
				NGUISettings.ambigiousFont = ttf.objectReferenceValue;
				isValid = true;
			}
		}

		GUILayout.EndHorizontal();

		EditorGUI.BeginDisabledGroup(!isValid);
		{
			UIFont uiFont = (fnt != null) ? fnt.objectReferenceValue as UIFont : null;
			Font dynFont = (ttf != null) ? ttf.objectReferenceValue as Font : null;

			if (uiFont != null && uiFont.isDynamic)
			{
				dynFont = uiFont.dynamicFont;
				uiFont = null;
			}

			if (dynFont != null)
			{
				GUILayout.BeginHorizontal();
				{
					EditorGUI.BeginDisabledGroup((ttf != null) ? ttf.hasMultipleDifferentValues : fnt.hasMultipleDifferentValues);
					
					SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
					NGUISettings.fontSize = prop.intValue;
					
					prop = NGUIEditorTools.DrawProperty("", serializedObject, "mFontStyle", GUILayout.MinWidth(40f));
					NGUISettings.fontStyle = (FontStyle)prop.intValue;
					
					GUILayout.Space(18f);
					EditorGUI.EndDisabledGroup();
				}
				GUILayout.EndHorizontal();

				NGUIEditorTools.DrawProperty("Material", serializedObject, "mMaterial");
			}
			else if (uiFont != null)
			{
				GUILayout.BeginHorizontal();
				SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));

				EditorGUI.BeginDisabledGroup(true);
				if (!serializedObject.isEditingMultipleObjects)
					GUILayout.Label(" Default: " + mLabel.defaultFontSize);
				EditorGUI.EndDisabledGroup();

				NGUISettings.fontSize = prop.intValue;
				GUILayout.EndHorizontal();
			}

			bool ww = GUI.skin.textField.wordWrap;
			GUI.skin.textField.wordWrap = true;
#if UNITY_3_5
			GUI.changed = false;
			SerializedProperty textField = serializedObject.FindProperty("mText");
			string text = EditorGUILayout.TextArea(textField.stringValue, GUI.skin.textArea, GUILayout.Height(100f));
			if (GUI.changed) textField.stringValue = text;
#else
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
			GUILayout.Space(-16f);
#endif
			GUILayout.BeginHorizontal();
			GUILayout.Space(4f);
			NGUIEditorTools.DrawProperty("", serializedObject, "mText", GUILayout.Height(80f));
			GUILayout.Space(4f);
			GUILayout.EndHorizontal();
#endif
			GUI.skin.textField.wordWrap = ww;

			NGUIEditorTools.DrawPaddedProperty("Alignment", serializedObject, "mAlignment");

			SerializedProperty ov = NGUIEditorTools.DrawPaddedProperty("Overflow", serializedObject, "mOverflow");
			NGUISettings.overflowStyle = (UILabel.Overflow)ov.intValue;

			if (dynFont != null)
				NGUIEditorTools.DrawPaddedProperty("Keep crisp", serializedObject, "keepCrispWhenShrunk");

			GUILayout.BeginHorizontal();
			GUILayout.Label("Spacing", GUILayout.Width(56f));
			NGUIEditorTools.SetLabelWidth(20f);
			NGUIEditorTools.DrawProperty("X", serializedObject, "mSpacingX", GUILayout.MinWidth(40f));
			NGUIEditorTools.DrawProperty("Y", serializedObject, "mSpacingY", GUILayout.MinWidth(40f));
			GUILayout.Space(18f);
			NGUIEditorTools.SetLabelWidth(80f);
			GUILayout.EndHorizontal();

			NGUIEditorTools.DrawProperty("Max Lines", serializedObject, "mMaxLineCount", GUILayout.Width(110f));

			GUILayout.BeginHorizontal();
			NGUIEditorTools.DrawProperty("Encoding", serializedObject, "mEncoding", GUILayout.Width(100f));
			GUILayout.Label("use emoticons and colors");
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			SerializedProperty gr = NGUIEditorTools.DrawProperty("Gradient", serializedObject, "mApplyGradient", GUILayout.Width(100f));
			if (gr.hasMultipleDifferentValues || gr.boolValue)
			{
				NGUIEditorTools.DrawProperty("", serializedObject, "mGradientBottom", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawProperty("", serializedObject, "mGradientTop", GUILayout.MinWidth(40f));
			}
			GUILayout.EndHorizontal();

			GUILayout.Space(4f);

			if (mLabel.supportEncoding && mLabel.bitmapFont != null && mLabel.bitmapFont.hasSymbols)
				NGUIEditorTools.DrawPaddedProperty("Symbols", serializedObject, "mSymbols");

			GUILayout.BeginHorizontal();
			SerializedProperty sp = NGUIEditorTools.DrawProperty("Effect", serializedObject, "mEffectStyle", GUILayout.MinWidth(170f));
			GUILayout.Space(18f);
			GUILayout.EndHorizontal();

			if (sp.hasMultipleDifferentValues || sp.boolValue)
				NGUIEditorTools.DrawProperty("Effect Color", serializedObject, "mEffectColor", GUILayout.MinWidth(30f));

			if (sp.hasMultipleDifferentValues || sp.boolValue)
			{
				GUILayout.BeginHorizontal();
				GUILayout.Label("Distance", GUILayout.Width(56f));
				NGUIEditorTools.SetLabelWidth(20f);
				NGUIEditorTools.DrawProperty("X", serializedObject, "mEffectDistance.x", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawProperty("Y", serializedObject, "mEffectDistance.y", GUILayout.MinWidth(40f));
				GUILayout.Space(18f);
				NGUIEditorTools.SetLabelWidth(80f);
				GUILayout.EndHorizontal();
			}
		}
		EditorGUI.EndDisabledGroup();
		return isValid;
	}
Exemple #52
0
	public override void OnInspectorGUI ()
	{
		mFont = target as UIFont;
		NGUIEditorTools.SetLabelWidth(80f);

		GUILayout.Space(6f);

		if (mFont.replacement != null)
		{
			mType = FontType.Reference;
			mReplacement = mFont.replacement;
		}
		else if (mFont.dynamicFont != null)
		{
			mType = FontType.Dynamic;
		}

		GUI.changed = false;
		GUILayout.BeginHorizontal();
		mType = (FontType)EditorGUILayout.EnumPopup("Font Type", mType);
		NGUIEditorTools.DrawPadding();
		GUILayout.EndHorizontal();

		if (GUI.changed)
		{
			if (mType == FontType.Bitmap)
				OnSelectFont(null);

			if (mType != FontType.Dynamic && mFont.dynamicFont != null)
				mFont.dynamicFont = null;
		}

		if (mType == FontType.Reference)
		{
			ComponentSelector.Draw<UIFont>(mFont.replacement, OnSelectFont, true);

			GUILayout.Space(6f);
			EditorGUILayout.HelpBox("You can have one font simply point to " +
				"another one. This is useful if you want to be " +
				"able to quickly replace the contents of one " +
				"font with another one, for example for " +
				"swapping an SD font with an HD one, or " +
				"replacing an English font with a Chinese " +
				"one. All the labels referencing this font " +
				"will update their references to the new one.", MessageType.Info);

			if (mReplacement != mFont && mFont.replacement != mReplacement)
			{
				NGUIEditorTools.RegisterUndo("Font Change", mFont);
				mFont.replacement = mReplacement;
				NGUITools.SetDirty(mFont);
			}
			return;
		}
		else if (mType == FontType.Dynamic)
		{
#if UNITY_3_5
			EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
			Font fnt = EditorGUILayout.ObjectField("TTF Font", mFont.dynamicFont, typeof(Font), false) as Font;
			
			if (fnt != mFont.dynamicFont)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFont = fnt;
			}

			Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

			if (mFont.material != mat)
			{
				NGUIEditorTools.RegisterUndo("Font Material", mFont);
				mFont.material = mat;
			}

			GUILayout.BeginHorizontal();
			int size = EditorGUILayout.IntField("Default Size", mFont.defaultSize, GUILayout.Width(120f));
			FontStyle style = (FontStyle)EditorGUILayout.EnumPopup(mFont.dynamicFontStyle);
			NGUIEditorTools.DrawPadding();
			GUILayout.EndHorizontal();

			if (size != mFont.defaultSize)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.defaultSize = size;
			}

			if (style != mFont.dynamicFontStyle)
			{
				NGUIEditorTools.RegisterUndo("Font change", mFont);
				mFont.dynamicFontStyle = style;
			}
#endif
		}
		else
		{
			ComponentSelector.Draw<UIAtlas>(mFont.atlas, OnSelectAtlas, true);

			if (mFont.atlas != null)
			{
				if (mFont.bmFont.isValid)
				{
					NGUIEditorTools.DrawAdvancedSpriteField(mFont.atlas, mFont.spriteName, SelectSprite, false);
				}
				EditorGUILayout.Space();
			}
			else
			{
				// No atlas specified -- set the material and texture rectangle directly
				Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

				if (mFont.material != mat)
				{
					NGUIEditorTools.RegisterUndo("Font Material", mFont);
					mFont.material = mat;
				}
			}

			// For updating the font's data when importing from an external source, such as the texture packer
			bool resetWidthHeight = false;

			if (mFont.atlas != null || mFont.material != null)
			{
				TextAsset data = EditorGUILayout.ObjectField("Import Data", null, typeof(TextAsset), false) as TextAsset;

				if (data != null)
				{
					NGUIEditorTools.RegisterUndo("Import Font Data", mFont);
					BMFontReader.Load(mFont.bmFont, NGUITools.GetHierarchy(mFont.gameObject), data.bytes);
					mFont.MarkAsChanged();
					resetWidthHeight = true;
					Debug.Log("Imported " + mFont.bmFont.glyphCount + " characters");
				}
			}

			if (mFont.bmFont.isValid)
			{
				Texture2D tex = mFont.texture;

				if (tex != null && mFont.atlas == null)
				{
					// Pixels are easier to work with than UVs
					Rect pixels = NGUIMath.ConvertToPixels(mFont.uvRect, tex.width, tex.height, false);

					// Automatically set the width and height of the rectangle to be the original font texture's dimensions
					if (resetWidthHeight)
					{
						pixels.width = mFont.texWidth;
						pixels.height = mFont.texHeight;
					}

					// Font sprite rectangle
					pixels = EditorGUILayout.RectField("Pixel Rect", pixels);

					// Convert the pixel coordinates back to UV coordinates
					Rect uvRect = NGUIMath.ConvertToTexCoords(pixels, tex.width, tex.height);

					if (mFont.uvRect != uvRect)
					{
						NGUIEditorTools.RegisterUndo("Font Pixel Rect", mFont);
						mFont.uvRect = uvRect;
					}
					//NGUIEditorTools.DrawSeparator();
					EditorGUILayout.Space();
				}
			}
		}

		// Dynamic fonts don't support emoticons
		if (!mFont.isDynamic && mFont.bmFont.isValid)
		{
			if (mFont.atlas != null)
			{
				if (NGUIEditorTools.DrawHeader("Symbols and Emoticons"))
				{
					NGUIEditorTools.BeginContents();

					List<BMSymbol> symbols = mFont.symbols;

					for (int i = 0; i < symbols.Count; )
					{
						BMSymbol sym = symbols[i];

						GUILayout.BeginHorizontal();
						GUILayout.Label(sym.sequence, GUILayout.Width(40f));
						if (NGUIEditorTools.DrawSpriteField(mFont.atlas, sym.spriteName, ChangeSymbolSprite, GUILayout.MinWidth(100f)))
							mSelectedSymbol = sym;

						if (GUILayout.Button("Edit", GUILayout.Width(40f)))
						{
							if (mFont.atlas != null)
							{
								NGUISettings.atlas = mFont.atlas;
								NGUISettings.selectedSprite = sym.spriteName;
								NGUIEditorTools.Select(mFont.atlas.gameObject);
							}
						}

						GUI.backgroundColor = Color.red;

						if (GUILayout.Button("X", GUILayout.Width(22f)))
						{
							NGUIEditorTools.RegisterUndo("Remove symbol", mFont);
							mSymbolSequence = sym.sequence;
							mSymbolSprite = sym.spriteName;
							symbols.Remove(sym);
							mFont.MarkAsChanged();
						}
						GUI.backgroundColor = Color.white;
						GUILayout.EndHorizontal();
						GUILayout.Space(4f);
						++i;
					}

					if (symbols.Count > 0)
					{
						GUILayout.Space(6f);
					}

					GUILayout.BeginHorizontal();
					mSymbolSequence = EditorGUILayout.TextField(mSymbolSequence, GUILayout.Width(40f));
					NGUIEditorTools.DrawSpriteField(mFont.atlas, mSymbolSprite, SelectSymbolSprite);

					bool isValid = !string.IsNullOrEmpty(mSymbolSequence) && !string.IsNullOrEmpty(mSymbolSprite);
					GUI.backgroundColor = isValid ? Color.green : Color.grey;

					if (GUILayout.Button("Add", GUILayout.Width(40f)) && isValid)
					{
						NGUIEditorTools.RegisterUndo("Add symbol", mFont);
						mFont.AddSymbol(mSymbolSequence, mSymbolSprite);
						mFont.MarkAsChanged();
						mSymbolSequence = "";
						mSymbolSprite = "";
					}
					GUI.backgroundColor = Color.white;
					GUILayout.EndHorizontal();

					if (symbols.Count == 0)
					{
						EditorGUILayout.HelpBox("Want to add an emoticon to your font? In the field above type ':)', choose a sprite, then hit the Add button.", MessageType.Info);
					}
					else GUILayout.Space(4f);

					NGUIEditorTools.EndContents();
				}
			}
		}

		if (mFont.bmFont != null && mFont.bmFont.isValid)
		{
			if (NGUIEditorTools.DrawHeader("Modify"))
			{
				NGUIEditorTools.BeginContents();

				UISpriteData sd = mFont.sprite;

				bool disable = (sd != null && (sd.paddingLeft != 0 || sd.paddingBottom != 0));
				EditorGUI.BeginDisabledGroup(disable || mFont.packedFontShader);

				EditorGUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				EditorGUILayout.BeginVertical();

				GUILayout.BeginHorizontal();
				GUILayout.BeginVertical();
				NGUISettings.foregroundColor = EditorGUILayout.ColorField("Foreground", NGUISettings.foregroundColor);
				NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);
				GUILayout.EndVertical();
				mCurve = EditorGUILayout.CurveField("", mCurve, GUILayout.Width(40f), GUILayout.Height(40f));
				GUILayout.EndHorizontal();

				if (GUILayout.Button("Add a Shadow")) ApplyEffect(Effect.Shadow, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Add a Soft Outline")) ApplyEffect(Effect.Outline, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Rebalance Colors")) ApplyEffect(Effect.Rebalance, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Alpha")) ApplyEffect(Effect.AlphaCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Foreground")) ApplyEffect(Effect.ForegroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Apply Curve to Background")) ApplyEffect(Effect.BackgroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);

				GUILayout.Space(10f);
				if (GUILayout.Button("Add Transparent Border (+1)")) ApplyEffect(Effect.Border, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
				if (GUILayout.Button("Remove Border (-1)")) ApplyEffect(Effect.Crop, NGUISettings.foregroundColor, NGUISettings.backgroundColor);

				EditorGUILayout.EndVertical();
				GUILayout.Space(20f);
				EditorGUILayout.EndHorizontal();

				EditorGUI.EndDisabledGroup();

				if (disable)
				{
					GUILayout.Space(3f);
					EditorGUILayout.HelpBox("The sprite used by this font has been trimmed and is not suitable for modification. " +
						"Try re-adding this sprite with 'Trim Alpha' disabled.", MessageType.Warning);
				}

				NGUIEditorTools.EndContents();
			}
		}

		// The font must be valid at this point for the rest of the options to show up
		if (mFont.isDynamic || mFont.bmFont.isValid)
		{
			if (mFont.atlas == null)
			{
				mView = View.Font;
				mUseShader = false;
			}
		}

		// Preview option
		if (!mFont.isDynamic && mFont.atlas != null)
		{
			GUILayout.BeginHorizontal();
			{
				mView = (View)EditorGUILayout.EnumPopup("Preview", mView);
				GUILayout.Label("Shader", GUILayout.Width(45f));
				mUseShader = EditorGUILayout.Toggle(mUseShader, GUILayout.Width(20f));
			}
			GUILayout.EndHorizontal();
		}
	}
Exemple #53
0
		/// <summary>
		/// Append the Select Font command to an existing Command object
		/// </summary>
		/// <param name="fontType">The font to select</param>
		public void SelectFont(FontType fontType)
		{
			AddOpcode(Opcode.UIDraw_SelectFont);
			AddParameter((byte)fontType);
		}
Exemple #54
0
	/// <summary>
	/// Draw the UI for this tool.
	/// </summary>

	void OnGUI ()
	{
		Object fnt = (Object)NGUISettings.FMFont ?? (Object)NGUISettings.BMFont;
		UIFont uiFont = (fnt as UIFont);

		NGUIEditorTools.SetLabelWidth(80f);
		GUILayout.Space(3f);

		NGUIEditorTools.DrawHeader("Input", true);
		NGUIEditorTools.BeginContents(false);

		GUILayout.BeginHorizontal();
		mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
		NGUIEditorTools.DrawPadding();
		GUILayout.EndHorizontal();
		Create create = Create.None;

		if (mType == FontType.ImportedBitmap)
		{
			NGUISettings.fontData = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset;
			NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
			NGUIEditorTools.EndContents();

			// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				NGUIEditorTools.DrawHeader("Output", true);
				NGUIEditorTools.BeginContents(false);
				ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
				NGUIEditorTools.EndContents();
			}
			EditorGUI.EndDisabledGroup();

			if (NGUISettings.fontData == null)
			{
				EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
					"Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
					"Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
			}
			else if (NGUISettings.fontTexture == null)
			{
				EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
			}
			else if (NGUISettings.atlas == null)
			{
				EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
					"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
			}

			EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
			{
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Import;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
			}
			EditorGUI.EndDisabledGroup();
		}
		else
		{
			GUILayout.BeginHorizontal();
			if (NGUIEditorTools.DrawPrefixButton("Source"))
				ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });

			Font ttf = EditorGUILayout.ObjectField(NGUISettings.FMFont, typeof(Font), false) as Font;
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			{
				NGUISettings.FMSize = EditorGUILayout.IntField("Size", NGUISettings.FMSize, GUILayout.Width(120f));

				if (mType == FontType.Dynamic)
				{
					NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
					NGUIEditorTools.DrawPadding();
				}
			}
			GUILayout.EndHorizontal();

			// Choose the font style if there are multiple faces present
			if (mType == FontType.GeneratedBitmap)
			{
				if (!FreeType.isPresent)
				{
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
					string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";
#else
					string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType64.dll" : "FreeType64.dylib";
#endif
					EditorGUILayout.HelpBox("Assets/NGUI/Editor/" + filename + " is missing", MessageType.Error);

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);

					if (GUILayout.Button("Find " + filename))
					{
						string path = EditorUtility.OpenFilePanel("Find " + filename, NGUISettings.currentPath,
							(Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");

						if (!string.IsNullOrEmpty(path))
						{
							if (System.IO.Path.GetFileName(path) == filename)
							{
								NGUISettings.currentPath = System.IO.Path.GetDirectoryName(path);
								NGUISettings.pathToFreeType = path;
							}
							else Debug.LogError("The library must be named '" + filename + "'");
						}
					}
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				else if (ttf != null)
				{
					string[] faces = FreeType.GetFaces(ttf);

					if (faces != null)
					{
						if (mFaceIndex >= faces.Length) mFaceIndex = 0;

						if (faces.Length > 1)
						{
							GUILayout.Label("Style", EditorStyles.boldLabel);
							for (int i = 0; i < faces.Length; ++i)
							{
								GUILayout.BeginHorizontal();
								GUILayout.Space(10f);
								if (DrawOption(i == mFaceIndex, " " + faces[i]))
									mFaceIndex = i;
								GUILayout.EndHorizontal();
							}
						}
					}

					NGUISettings.fontKerning = EditorGUILayout.Toggle("Kerning", NGUISettings.fontKerning);

					GUILayout.Label("Characters", EditorStyles.boldLabel);

					CharacterMap cm = characterMap;

					GUILayout.BeginHorizontal(GUILayout.Width(100f));
					GUILayout.BeginVertical();
					GUI.changed = false;
					if (DrawOption(cm == CharacterMap.Numeric, " Numeric")) cm = CharacterMap.Numeric;
					if (DrawOption(cm == CharacterMap.Ascii, " ASCII")) cm = CharacterMap.Ascii;
					if (DrawOption(cm == CharacterMap.Latin, " Latin")) cm = CharacterMap.Latin;
					if (DrawOption(cm == CharacterMap.Custom, " Custom")) cm = CharacterMap.Custom;
					if (GUI.changed) characterMap = cm;
					GUILayout.EndVertical();

					EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
					{
						if (cm != CharacterMap.Custom)
						{
							string chars = "";

							if (cm == CharacterMap.Ascii)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);
							}
							else if (cm == CharacterMap.Numeric)
							{
								chars = "0123456789";
							}
							else if (cm == CharacterMap.Latin)
							{
								for (int i = 33; i < 127; ++i)
									chars += System.Convert.ToChar(i);

								for (int i = 161; i < 256; ++i)
									chars += System.Convert.ToChar(i);
							}

							NGUISettings.charsToInclude = chars;
						}

						GUI.changed = false;

						string text = NGUISettings.charsToInclude;

						if (cm == CharacterMap.Custom)
						{
							text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}
						else
						{
							GUILayout.Label(text, GUI.skin.textArea,
								GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
						}

						if (GUI.changed)
						{
							string final = "";

							for (int i = 0; i < text.Length; ++i)
							{
								char c = text[i];
								if (c < 33) continue;
								string s = c.ToString();
								if (!final.Contains(s)) final += s;
							}

							if (final.Length > 0)
							{
								char[] chars = final.ToCharArray();
								System.Array.Sort(chars);
								final = new string(chars);
							}
							else final = "";

							NGUISettings.charsToInclude = final;
						}
					}
					EditorGUI.EndDisabledGroup();
					GUILayout.EndHorizontal();
				}
			}
			NGUIEditorTools.EndContents();

			if (mType == FontType.Dynamic)
			{
				EditorGUI.BeginDisabledGroup(ttf == null);
				GUILayout.BeginHorizontal();
				GUILayout.Space(20f);
				if (GUILayout.Button("Create the Font")) create = Create.Dynamic;
				GUILayout.Space(20f);
				GUILayout.EndHorizontal();
				EditorGUI.EndDisabledGroup();
#if UNITY_3_5
				EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
				// Helpful info
				if (ttf == null)
				{
					EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
				}
				EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
			}
			else
			{
				bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.AssetDatabase.GetAssetPath(ttf));

				// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
				EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
				{
					NGUIEditorTools.DrawHeader("Output", true);
					NGUIEditorTools.BeginContents(false);
					ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
					NGUIEditorTools.EndContents();

					if (ttf == null)
					{
						EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
					}
					else if (isBuiltIn)
					{
						EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
					}
					else if (NGUISettings.atlas == null)
					{
						EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
							"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
					}

					GUILayout.BeginHorizontal();
					GUILayout.Space(20f);
					if (GUILayout.Button("Create the Font")) create = Create.Bitmap;
					GUILayout.Space(20f);
					GUILayout.EndHorizontal();
				}
				EditorGUI.EndDisabledGroup();
			}
		}

		if (create == Create.None) return;

		// Open the "Save As" file dialog
#if UNITY_3_5
		string prefabPath = EditorUtility.SaveFilePanel("Save As",
			NGUISettings.currentPath, "New Font.prefab", "prefab");
#else
		string prefabPath = EditorUtility.SaveFilePanelInProject("Save As",
			"New Font.prefab", "prefab", "Save font as...", NGUISettings.currentPath);
#endif
		if (string.IsNullOrEmpty(prefabPath)) return;
		NGUISettings.currentPath = System.IO.Path.GetDirectoryName(prefabPath);

		// Load the font's prefab
		GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
		Object prefab = null;
		string fontName;

		// Font doesn't exist yet
		if (go == null || go.GetComponent<UIFont>() == null)
		{
			// Create a new prefab for the atlas
			prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

			fontName = prefabPath.Replace(".prefab", "");
			fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);

			// Create a new game object for the font
			go = new GameObject(fontName);
			uiFont = go.AddComponent<UIFont>();
		}
		else
		{
			uiFont = go.GetComponent<UIFont>();
			fontName = go.name;
		}

		if (create == Create.Dynamic)
		{
			uiFont.atlas = null;
			uiFont.dynamicFont = NGUISettings.FMFont;
			uiFont.dynamicFontStyle = NGUISettings.fontStyle;
			uiFont.defaultSize = NGUISettings.FMSize;
		}
		else if (create == Create.Import)
		{
			Material mat = null;

			if (NGUISettings.atlas != null)
			{
				// Add the font's texture to the atlas
				UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
			}
			else
			{
				// Create a material for the font
				string matPath = prefabPath.Replace(".prefab", ".mat");
				mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

				// If the material doesn't exist, create it
				if (mat == null)
				{
					Shader shader = Shader.Find("Unlit/Transparent Colored");
					mat = new Material(shader);

					// Save the material
					AssetDatabase.CreateAsset(mat, matPath);
					AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

					// Load the material so it's usable
					mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
				}

				mat.mainTexture = NGUISettings.fontTexture;
			}

			uiFont.dynamicFont = null;
			BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);

			if (NGUISettings.atlas == null)
			{
				uiFont.atlas = null;
				uiFont.material = mat;
			}
			else
			{
				uiFont.spriteName = NGUISettings.fontTexture.name;
				uiFont.atlas = NGUISettings.atlas;
			}
			NGUISettings.FMSize = uiFont.defaultSize;
		}
		else if (create == Create.Bitmap)
		{
			// Create the bitmap font
			BMFont bmFont;
			Texture2D tex;

			if (FreeType.CreateFont(
				NGUISettings.FMFont,
				NGUISettings.FMSize, mFaceIndex,
				NGUISettings.fontKerning,
				NGUISettings.charsToInclude, 1, out bmFont, out tex))
			{
				uiFont.bmFont = bmFont;
				tex.name = fontName;

				if (NGUISettings.atlas != null)
				{
					// Add this texture to the atlas and destroy it
					UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
					NGUITools.DestroyImmediate(tex);
					NGUISettings.fontTexture = null;
					tex = null;

					uiFont.atlas = NGUISettings.atlas;
					uiFont.spriteName = fontName;
				}
				else
				{
					string texPath = prefabPath.Replace(".prefab", ".png");
					string matPath = prefabPath.Replace(".prefab", ".mat");

					byte[] png = tex.EncodeToPNG();
					FileStream fs = File.OpenWrite(texPath);
					fs.Write(png, 0, png.Length);
					fs.Close();

					// See if the material already exists
					Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

					// If the material doesn't exist, create it
					if (mat == null)
					{
						Shader shader = Shader.Find("Unlit/Transparent Colored");
						mat = new Material(shader);

						// Save the material
						AssetDatabase.CreateAsset(mat, matPath);
						AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

						// Load the material so it's usable
						mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
					}
					else AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

					// Re-load the texture
					tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;

					// Assign the texture
					mat.mainTexture = tex;
					NGUISettings.fontTexture = tex;

					uiFont.atlas = null;
					uiFont.material = mat;
				}
			}
			else return;
		}

		if (prefab != null)
		{
			// Update the prefab
			PrefabUtility.ReplacePrefab(go, prefab);
			DestroyImmediate(go);
			AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

			// Select the atlas
			go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
			uiFont = go.GetComponent<UIFont>();
		}

		if (uiFont != null)
		{
			NGUISettings.FMFont = null;
			NGUISettings.BMFont = uiFont;
		}
		MarkAsChanged();
		Selection.activeGameObject = go;
	}
    public override void OnInspectorGUI()
    {
        mFont = target as UIFont;
        NGUIEditorTools.SetLabelWidth(80f);

        GUILayout.Space(6f);

        if (mFont.replacement != null)
        {
            mType = FontType.Reference;
            mReplacement = mFont.replacement;
        }
        else if (mFont.dynamicFont != null)
        {
            mType = FontType.Dynamic;
        }

        GUILayout.BeginHorizontal();
        FontType fontType = (FontType)EditorGUILayout.EnumPopup("Font Type", mType);
        GUILayout.Space(18f);
        GUILayout.EndHorizontal();

        if (mType != fontType)
        {
            if (fontType == FontType.Normal)
            {
                OnSelectFont(null);
            }
            else
            {
                mType = fontType;
            }

            if (mType != FontType.Dynamic && mFont.dynamicFont != null)
                mFont.dynamicFont = null;
        }

        if (mType == FontType.Reference)
        {
            ComponentSelector.Draw<UIFont>(mFont.replacement, OnSelectFont);

            GUILayout.Space(6f);
            EditorGUILayout.HelpBox("You can have one font simply point to " +
                "another one. This is useful if you want to be " +
                "able to quickly replace the contents of one " +
                "font with another one, for example for " +
                "swapping an SD font with an HD one, or " +
                "replacing an English font with a Chinese " +
                "one. All the labels referencing this font " +
                "will update their references to the new one.", MessageType.Info);

            if (mReplacement != mFont && mFont.replacement != mReplacement)
            {
                NGUIEditorTools.RegisterUndo("Font Change", mFont);
                mFont.replacement = mReplacement;
                UnityEditor.EditorUtility.SetDirty(mFont);
            }
            return;
        }
        else if (mType == FontType.Dynamic)
        {
        #if UNITY_3_5
            EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
        #else
            Font fnt = EditorGUILayout.ObjectField("TTF Font", mFont.dynamicFont, typeof(Font), false) as Font;

            if (fnt != mFont.dynamicFont)
            {
                NGUIEditorTools.RegisterUndo("Font change", mFont);
                mFont.dynamicFont = fnt;
            }

            Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

            if (mFont.material != mat)
            {
                NGUIEditorTools.RegisterUndo("Font Material", mFont);
                mFont.material = mat;
            }

            GUILayout.BeginHorizontal();
            int size = EditorGUILayout.IntField("Size", mFont.dynamicFontSize, GUILayout.Width(120f));
            FontStyle style = (FontStyle)EditorGUILayout.EnumPopup(mFont.dynamicFontStyle);
            GUILayout.Space(18f);
            GUILayout.EndHorizontal();

            if (size != mFont.dynamicFontSize)
            {
                NGUIEditorTools.RegisterUndo("Font change", mFont);
                mFont.dynamicFontSize = size;
            }

            if (style != mFont.dynamicFontStyle)
            {
                NGUIEditorTools.RegisterUndo("Font change", mFont);
                mFont.dynamicFontStyle = style;
            }
        #endif
        }
        else
        {
            NGUIEditorTools.DrawSeparator();

            ComponentSelector.Draw<UIAtlas>(mFont.atlas, OnSelectAtlas);

            if (mFont.atlas != null)
            {
                if (mFont.bmFont.isValid)
                {
                    NGUIEditorTools.AdvancedSpriteField(mFont.atlas, mFont.spriteName, SelectSprite, false);
                }
                EditorGUILayout.Space();
            }
            else
            {
                // No atlas specified -- set the material and texture rectangle directly
                Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;

                if (mFont.material != mat)
                {
                    NGUIEditorTools.RegisterUndo("Font Material", mFont);
                    mFont.material = mat;
                }
            }

            // For updating the font's data when importing from an external source, such as the texture packer
            bool resetWidthHeight = false;

            if (mFont.atlas != null || mFont.material != null)
            {
                TextAsset data = EditorGUILayout.ObjectField("Import Data", null, typeof(TextAsset), false) as TextAsset;

                if (data != null)
                {
                    NGUIEditorTools.RegisterUndo("Import Font Data", mFont);
                    BMFontReader.Load(mFont.bmFont, NGUITools.GetHierarchy(mFont.gameObject), data.bytes);
                    mFont.MarkAsDirty();
                    resetWidthHeight = true;
                    Debug.Log("Imported " + mFont.bmFont.glyphCount + " characters");
                }
            }

            if (mFont.bmFont.isValid)
            {
                Color green = new Color(0.4f, 1f, 0f, 1f);
                Texture2D tex = mFont.texture;

                if (tex != null)
                {
                    if (mFont.atlas == null)
                    {
                        // Pixels are easier to work with than UVs
                        Rect pixels = NGUIMath.ConvertToPixels(mFont.uvRect, tex.width, tex.height, false);

                        // Automatically set the width and height of the rectangle to be the original font texture's dimensions
                        if (resetWidthHeight)
                        {
                            pixels.width = mFont.texWidth;
                            pixels.height = mFont.texHeight;
                        }

                        // Font sprite rectangle
                        GUI.backgroundColor = green;
                        pixels = EditorGUILayout.RectField("Pixel Rect", pixels);
                        GUI.backgroundColor = Color.white;

                        // Create a button that can make the coordinates pixel-perfect on click
                        GUILayout.BeginHorizontal();
                        {
                            Rect corrected = NGUIMath.MakePixelPerfect(pixels);

                            if (corrected == pixels)
                            {
                                GUI.color = Color.grey;
                                GUILayout.Button("Make Pixel-Perfect");
                                GUI.color = Color.white;
                            }
                            else if (GUILayout.Button("Make Pixel-Perfect"))
                            {
                                pixels = corrected;
                                GUI.changed = true;
                            }
                        }
                        GUILayout.EndHorizontal();

                        // Convert the pixel coordinates back to UV coordinates
                        Rect uvRect = NGUIMath.ConvertToTexCoords(pixels, tex.width, tex.height);

                        if (mFont.uvRect != uvRect)
                        {
                            NGUIEditorTools.RegisterUndo("Font Pixel Rect", mFont);
                            mFont.uvRect = uvRect;
                        }
                        //NGUIEditorTools.DrawSeparator();
                        EditorGUILayout.Space();
                    }
                }
            }
        }

        // The font must be valid at this point for the rest of the options to show up
        if (mFont.isDynamic || mFont.bmFont.isValid)
        {
            // Font spacing
            GUILayout.BeginHorizontal();
            {
                NGUIEditorTools.SetLabelWidth(0f);
                GUILayout.Label("Spacing", GUILayout.Width(60f));
                GUILayout.Label("X", GUILayout.Width(12f));
                int x = EditorGUILayout.IntField(mFont.horizontalSpacing);
                GUILayout.Label("Y", GUILayout.Width(12f));
                int y = EditorGUILayout.IntField(mFont.verticalSpacing);
                GUILayout.Space(18f);
                NGUIEditorTools.SetLabelWidth(80f);

                if (mFont.horizontalSpacing != x || mFont.verticalSpacing != y)
                {
                    NGUIEditorTools.RegisterUndo("Font Spacing", mFont);
                    mFont.horizontalSpacing = x;
                    mFont.verticalSpacing = y;
                }
            }
            GUILayout.EndHorizontal();

            if (mFont.atlas == null)
            {
                mView = View.Font;
                mUseShader = false;

                float pixelSize = EditorGUILayout.FloatField("Pixel Size", mFont.pixelSize, GUILayout.Width(120f));

                if (pixelSize != mFont.pixelSize)
                {
                    NGUIEditorTools.RegisterUndo("Font Change", mFont);
                    mFont.pixelSize = pixelSize;
                }
            }
            EditorGUILayout.Space();
        }

        // Preview option
        if (!mFont.isDynamic && mFont.atlas != null)
        {
            GUILayout.BeginHorizontal();
            {
                mView = (View)EditorGUILayout.EnumPopup("Preview", mView);
                GUILayout.Label("Shader", GUILayout.Width(45f));
                mUseShader = EditorGUILayout.Toggle(mUseShader, GUILayout.Width(20f));
            }
            GUILayout.EndHorizontal();
        }

        // Dynamic fonts don't support emoticons
        if (!mFont.isDynamic && mFont.bmFont.isValid)
        {
            if (mFont.atlas != null)
            {
                if (NGUIEditorTools.DrawHeader("Symbols and Emoticons"))
                {
                    NGUIEditorTools.BeginContents();

                    List<BMSymbol> symbols = mFont.symbols;

                    for (int i = 0; i < symbols.Count; )
                    {
                        BMSymbol sym = symbols[i];

                        GUILayout.BeginHorizontal();
                        GUILayout.Label(sym.sequence, GUILayout.Width(40f));
                        if (NGUIEditorTools.SimpleSpriteField(mFont.atlas, sym.spriteName, ChangeSymbolSprite))
                            mSelectedSymbol = sym;

                        if (GUILayout.Button("Edit", GUILayout.Width(40f)))
                        {
                            if (mFont.atlas != null)
                            {
                                NGUISettings.selectedSprite = sym.spriteName;
                                NGUIEditorTools.Select(mFont.atlas.gameObject);
                            }
                        }

                        GUI.backgroundColor = Color.red;

                        if (GUILayout.Button("X", GUILayout.Width(22f)))
                        {
                            NGUIEditorTools.RegisterUndo("Remove symbol", mFont);
                            mSymbolSequence = sym.sequence;
                            mSymbolSprite = sym.spriteName;
                            symbols.Remove(sym);
                            mFont.MarkAsDirty();
                        }
                        GUI.backgroundColor = Color.white;
                        GUILayout.EndHorizontal();
                        GUILayout.Space(4f);
                        ++i;
                    }

                    if (symbols.Count > 0)
                    {
                        GUILayout.Space(6f);
                    }

                    GUILayout.BeginHorizontal();
                    mSymbolSequence = EditorGUILayout.TextField(mSymbolSequence, GUILayout.Width(40f));
                    NGUIEditorTools.SimpleSpriteField(mFont.atlas, mSymbolSprite, SelectSymbolSprite);

                    bool isValid = !string.IsNullOrEmpty(mSymbolSequence) && !string.IsNullOrEmpty(mSymbolSprite);
                    GUI.backgroundColor = isValid ? Color.green : Color.grey;

                    if (GUILayout.Button("Add", GUILayout.Width(40f)) && isValid)
                    {
                        NGUIEditorTools.RegisterUndo("Add symbol", mFont);
                        mFont.AddSymbol(mSymbolSequence, mSymbolSprite);
                        mFont.MarkAsDirty();
                        mSymbolSequence = "";
                        mSymbolSprite = "";
                    }
                    GUI.backgroundColor = Color.white;
                    GUILayout.EndHorizontal();

                    if (symbols.Count == 0)
                    {
                        EditorGUILayout.HelpBox("Want to add an emoticon to your font? In the field above type ':)', choose a sprite, then hit the Add button.", MessageType.Info);
                    }
                    else GUILayout.Space(4f);

                    NGUIEditorTools.EndContents();
                }
            }
        }
    }
 public static FormattedText GetFormattedText(string textToFormat, FontType fontType, double fontSize, Brush brush)
 {
     return GetFormattedText(textToFormat, fontType, fontSize, FontStyles.Normal, FontWeights.Normal, brush);
 }
 public static FormattedText GetFormattedText(string textToFormat, FontType fontType, double fontSize, FontStyle fontStyle, FontWeight fontWeight, Brush brush)
 {
     Typeface typeface = GetTypeface(fontType, fontStyle, fontWeight);
     return new FormattedText(textToFormat, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, typeface, fontSize, brush);
 }
	protected override void OnEnable ()
	{
		base.OnEnable();
		SerializedProperty bit = serializedObject.FindProperty("mFont");
		mFontType = (bit != null && bit.objectReferenceValue != null) ? FontType.NGUI : FontType.Unity;
	}
	/// <summary>
	/// Draw the label's properties.
	/// </summary>

	protected override bool ShouldDrawProperties ()
	{
		mLabel = mWidget as UILabel;

		GUILayout.BeginHorizontal();

#if DYNAMIC_FONT
		mFontType = (FontType)EditorGUILayout.EnumPopup(mFontType, "DropDown", GUILayout.Width(74f));
		if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(64f)))
#else
		mFontType = FontType.NGUI;
		if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(74f)))
#endif
		{
			if (mFontType == FontType.NGUI)
			{
				ComponentSelector.Show<UIFont>(OnNGUIFont);
			}
			else
			{
				ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
			}
		}

		bool isValid = false;
		SerializedProperty fnt = null;
		SerializedProperty ttf = null;

		if (mFontType == FontType.NGUI)
		{
			GUI.changed = false;
			fnt = NGUIEditorTools.DrawProperty("", serializedObject, "mFont", GUILayout.MinWidth(40f));

			if (fnt.objectReferenceValue != null)
			{
				if (GUI.changed) serializedObject.FindProperty("mTrueTypeFont").objectReferenceValue = null;
				NGUISettings.ambigiousFont = fnt.objectReferenceValue;
				isValid = true;
			}
		}
		else
		{
			GUI.changed = false;
			ttf = NGUIEditorTools.DrawProperty("", serializedObject, "mTrueTypeFont", GUILayout.MinWidth(40f));

			if (ttf.objectReferenceValue != null)
			{
				if (GUI.changed) serializedObject.FindProperty("mFont").objectReferenceValue = null;
				NGUISettings.ambigiousFont = ttf.objectReferenceValue;
				isValid = true;
			}
		}

		GUILayout.EndHorizontal();

		if (mFontType == FontType.Unity)
		{
			EditorGUILayout.HelpBox("Dynamic fonts suffer from issues in Unity itself where your characters may disappear, get garbled, or just not show at times. Use this feature at your own risk.\n\n" +
				"When you do run into such issues, please submit a Bug Report to Unity via Help -> Report a Bug (as this is will be a Unity bug, not an NGUI one).", MessageType.Warning);
		}

		EditorGUI.BeginDisabledGroup(!isValid);
		{
			UIFont uiFont = (fnt != null) ? fnt.objectReferenceValue as UIFont : null;
			Font dynFont = (ttf != null) ? ttf.objectReferenceValue as Font : null;

			if (uiFont != null && uiFont.isDynamic)
			{
				dynFont = uiFont.dynamicFont;
				uiFont = null;
			}

			if (dynFont != null)
			{
				GUILayout.BeginHorizontal();
				{
					EditorGUI.BeginDisabledGroup((ttf != null) ? ttf.hasMultipleDifferentValues : fnt.hasMultipleDifferentValues);
					
					SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
					NGUISettings.fontSize = prop.intValue;
					
					prop = NGUIEditorTools.DrawProperty("", serializedObject, "mFontStyle", GUILayout.MinWidth(40f));
					NGUISettings.fontStyle = (FontStyle)prop.intValue;
					
					NGUIEditorTools.DrawPadding();
					EditorGUI.EndDisabledGroup();
				}
				GUILayout.EndHorizontal();

				NGUIEditorTools.DrawProperty("Material", serializedObject, "mMaterial");
			}
			else if (uiFont != null)
			{
				GUILayout.BeginHorizontal();
				SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));

				EditorGUI.BeginDisabledGroup(true);
				if (!serializedObject.isEditingMultipleObjects)
				{
					if (mLabel.overflowMethod == UILabel.Overflow.ShrinkContent)
						GUILayout.Label(" Actual: " + mLabel.finalFontSize + "/" + mLabel.defaultFontSize);
					else GUILayout.Label(" Default: " + mLabel.defaultFontSize);
				}
				EditorGUI.EndDisabledGroup();

				NGUISettings.fontSize = prop.intValue;
				GUILayout.EndHorizontal();
			}

			bool ww = GUI.skin.textField.wordWrap;
			GUI.skin.textField.wordWrap = true;
			SerializedProperty sp = serializedObject.FindProperty("mText");

			if (sp.hasMultipleDifferentValues)
			{
				NGUIEditorTools.DrawProperty("", sp, GUILayout.Height(128f));
			}
			else
			{
				GUIStyle style = new GUIStyle(EditorStyles.textField);
				style.wordWrap = true;

				float height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 100f);
				bool offset = true;

				if (height > 90f)
				{
					offset = false;
					height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 20f);
				}
				else
				{
					GUILayout.BeginHorizontal();
					GUILayout.BeginVertical(GUILayout.Width(76f));
					GUILayout.Space(3f);
					GUILayout.Label("Text");
					GUILayout.EndVertical();
					GUILayout.BeginVertical();
				}
				Rect rect = EditorGUILayout.GetControlRect(GUILayout.Height(height));

				GUI.changed = false;
				string text = EditorGUI.TextArea(rect, sp.stringValue, style);
				if (GUI.changed) sp.stringValue = text;

				if (offset)
				{
					GUILayout.EndVertical();
					GUILayout.EndHorizontal();
				}
			}

			GUI.skin.textField.wordWrap = ww;

			SerializedProperty ov = NGUIEditorTools.DrawPaddedProperty("Overflow", serializedObject, "mOverflow");
			NGUISettings.overflowStyle = (UILabel.Overflow)ov.intValue;

			NGUIEditorTools.DrawPaddedProperty("Alignment", serializedObject, "mAlignment");

			if (dynFont != null)
				NGUIEditorTools.DrawPaddedProperty("Keep crisp", serializedObject, "keepCrispWhenShrunk");

			EditorGUI.BeginDisabledGroup(mLabel.bitmapFont != null && mLabel.bitmapFont.packedFontShader);
			GUILayout.BeginHorizontal();
			SerializedProperty gr = NGUIEditorTools.DrawProperty("Gradient", serializedObject, "mApplyGradient",
			GUILayout.Width(95f));

			EditorGUI.BeginDisabledGroup(!gr.hasMultipleDifferentValues && !gr.boolValue);
			{
				NGUIEditorTools.SetLabelWidth(30f);
				NGUIEditorTools.DrawProperty("Top", serializedObject, "mGradientTop", GUILayout.MinWidth(40f));
				GUILayout.EndHorizontal();
				GUILayout.BeginHorizontal();
				NGUIEditorTools.SetLabelWidth(50f);
				GUILayout.Space(79f);

				NGUIEditorTools.DrawProperty("Bottom", serializedObject, "mGradientBottom", GUILayout.MinWidth(40f));
				NGUIEditorTools.SetLabelWidth(80f);
			}
			EditorGUI.EndDisabledGroup();
			GUILayout.EndHorizontal();

			GUILayout.BeginHorizontal();
			GUILayout.Label("Effect", GUILayout.Width(76f));
			sp = NGUIEditorTools.DrawProperty("", serializedObject, "mEffectStyle", GUILayout.MinWidth(16f));

			EditorGUI.BeginDisabledGroup(!sp.hasMultipleDifferentValues && !sp.boolValue);
			{
				NGUIEditorTools.DrawProperty("", serializedObject, "mEffectColor", GUILayout.MinWidth(10f));
				GUILayout.EndHorizontal();

				GUILayout.BeginHorizontal();
				{
					GUILayout.Label(" ", GUILayout.Width(56f));
					NGUIEditorTools.SetLabelWidth(20f);
					NGUIEditorTools.DrawProperty("X", serializedObject, "mEffectDistance.x", GUILayout.MinWidth(40f));
					NGUIEditorTools.DrawProperty("Y", serializedObject, "mEffectDistance.y", GUILayout.MinWidth(40f));
					NGUIEditorTools.DrawPadding();
					NGUIEditorTools.SetLabelWidth(80f);
				}
			}
			EditorGUI.EndDisabledGroup();
			GUILayout.EndHorizontal();
			EditorGUI.EndDisabledGroup();

			sp = NGUIEditorTools.DrawProperty("Float spacing", serializedObject, "mUseFloatSpacing", GUILayout.Width(100f));

			if (!sp.boolValue)
			{
				GUILayout.BeginHorizontal();
				GUILayout.Label("Spacing", GUILayout.Width(56f));
				NGUIEditorTools.SetLabelWidth(20f);
				NGUIEditorTools.DrawProperty("X", serializedObject, "mSpacingX", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawProperty("Y", serializedObject, "mSpacingY", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawPadding();
				NGUIEditorTools.SetLabelWidth(80f);
				GUILayout.EndHorizontal();
			}
			else
			{
				GUILayout.BeginHorizontal();
				GUILayout.Label("Spacing", GUILayout.Width(56f));
				NGUIEditorTools.SetLabelWidth(20f);
				NGUIEditorTools.DrawProperty("X", serializedObject, "mFloatSpacingX", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawProperty("Y", serializedObject, "mFloatSpacingY", GUILayout.MinWidth(40f));
				NGUIEditorTools.DrawPadding();
				NGUIEditorTools.SetLabelWidth(80f);
				GUILayout.EndHorizontal();
			}
			
			NGUIEditorTools.DrawProperty("Max Lines", serializedObject, "mMaxLineCount", GUILayout.Width(110f));

			GUILayout.BeginHorizontal();
			sp = NGUIEditorTools.DrawProperty("BBCode", serializedObject, "mEncoding", GUILayout.Width(100f));
			EditorGUI.BeginDisabledGroup(!sp.boolValue || mLabel.bitmapFont == null || !mLabel.bitmapFont.hasSymbols);
			NGUIEditorTools.SetLabelWidth(60f);
			NGUIEditorTools.DrawPaddedProperty("Symbols", serializedObject, "mSymbols");
			NGUIEditorTools.SetLabelWidth(80f);
			EditorGUI.EndDisabledGroup();
			GUILayout.EndHorizontal();
		}
		EditorGUI.EndDisabledGroup();
		return isValid;
	}
 static FontFamily CreateFontFamily(FontType ft)
 {
     switch (ft)
     {
         case FontType.STIXGeneral:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXGeneral");
         case FontType.STIXIntegralsD:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXIntegralsD");
         case FontType.STIXIntegralsSm:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXIntegralsSm");
         case FontType.STIXIntegralsUp:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXIntegralsUp");
         case FontType.STIXIntegralsUpD:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXIntegralsUpD");
         case FontType.STIXIntegralsUpSm:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXIntegralsUpSm");
         case FontType.STIXNonUnicode:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXNonUnicode");
         case FontType.STIXSizeFiveSym:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXSizeFiveSym");
         case FontType.STIXSizeFourSym:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXSizeFourSym");
         case FontType.STIXSizeOneSym:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXSizeOneSym");
         case FontType.STIXSizeThreeSym:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXSizeThreeSym");
         case FontType.STIXSizeTwoSym:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXSizeTwoSym");
         case FontType.STIXVariants:
             return new FontFamily(new Uri("pack://application:,,,/STIX/"), "./#STIXVariants");
         case FontType.Arial:
             return new FontFamily("Arial");
         case FontType.ArialBlack:
             return new FontFamily("Arial Black");
         case FontType.ComicSansMS:
             return new FontFamily("Comic Sans MS");
         case FontType.Courier:
             return new FontFamily("Courier");
         case FontType.CourierNew:
             return new FontFamily("Courier New");
         case FontType.Georgia:
             return new FontFamily("Georgia");
         case FontType.Impact:
             return new FontFamily("Impact");
         case FontType.LucidaConsole:
             return new FontFamily("Lucida Console");
         case FontType.LucidaSansUnicode:
             return new FontFamily("Lucida Sans Unicode");
         case FontType.MSSerif:
             return new FontFamily("MS Serif");
         case FontType.MSSansSerif:
             return new FontFamily("MS Sans Serif");
         case FontType.PalatinoLinotype:
             return new FontFamily("Palatino Linotype");
         case FontType.Segoe:
             return new FontFamily("Segoe UI");
         case FontType.Symbol:
             return new FontFamily("Symbol");
         case FontType.Tahoma:
             return new FontFamily("Tahoma");
         case FontType.TimesNewRoman:
             return new FontFamily("Times New Roman");
         case FontType.TrebuchetMS:
             return new FontFamily("Trebuchet MS");
         case FontType.Verdana:
             return new FontFamily("Verdana");
         case FontType.Webdings:
             return new FontFamily("Webdings");
         case FontType.Wingdings:
             return new FontFamily("Wingdings");
     }
     return new FontFamily("Segoe UI");
 }