Ma Ning's Windows Phone 7 Development tutorial (4) -- xNa displays Chinese Fonts

Source: Internet
Author: User
ArticleDirectory
    • Draw font
    • Add Chinese support
    • Related Resources


I 've been so diligent recently that it's incredible. Yesterday, a friend posted a message in the previous article, criticizing Windows Phone 7 for its lack of support for the Chinese version. There is a process in everything. Before the Chinese version is released, let's find a solution by ourselves. Silverlight for Windows Phone doesn't matter. Someone will come up with a solution. How can I display Chinese Characters in Windows Phone 7 games? Drag the man who says "texture" out and kill him! Because xNa 4.0 supports Chinese characters, it is highly related to the xNa font support method.



ExampleCode:



Http://files.cnblogs.com/aawolf/XNA_aawolf_SIP_Chinese.rar


Draw font


Let's take a look at how xNa draws fonts. The descriptions on msdn are good:



Http://msdn.microsoft.com/en-us/library/bb447673.aspx



We don't have to worry about font authorization. I would like to remind you that before using a certain font, you should first confirm whether it can be used and then distributed. The first step to draw a font is to create a Sprite font. The font file used in xNa is called sprite font and the file extension is. spritefont. xNa supports converting the font from. TTF to. spritefont.



First, find the windowsphonegame1content project in Solution Explorer of vs 2010, right-click "add"-"New Folder" in the menu, name the new folder as font, and right-click on font, select "add"-"new item", and then select "Sprite font" in the dialog box to name the font file startfont.






Double-click the startfont. spritefont file in Solution Explorer. We will open an XML file, saving the XML comments:


 
 
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
  <Asset Type="Graphics:FontDescription">

    <FontName>Kootenay</FontName>
    <Size>30</Size>
    <Spacing>0</Spacing>
    <UseKerning>true</UseKerning>
    <Style>Regular</Style>

    <CharacterRegions>
      <CharacterRegion>
        <Start>&#32;</Start>
        <End>&#126;</End>
      </CharacterRegion>
    </CharacterRegions>
  </Asset>
</XnaContent>


According to the XML annotations, we can easily understand each item's function, only the highlighted part: fontname, font name, size, font size, style, specifies whether the font is bold or italic. characterregion indicates the font range. Currently, only ASCII fonts are displayed. This is also very suitable for game development, and the game does not need to provide complete character set support.



Next, draw the code. First, add the spritefont variable to the class:


 




 
   public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont StartFont;
        SpriteFont YaheiFont; static string Text = "";


We also added a text variable that can be used to obtain user input strings from the SIP keypad. Then there is the loadcontent function:


  


       /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            StartFont = Content.Load<SpriteFont>(@"Font\StartFont");
            YaheiFont = Content.Load<SpriteFont>(@"Font\Yahei");
        }


Note the path of the font file: You can put the content resource in another DLL to easily replace resources with the game. In terms of the path, you only need to specify the folder. By the way, the Chinese font has been added. To obtain the SIP input, modify the update method as follows:


 protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            if (Text == "" && !Guide.IsVisible)
                Guide.BeginShowKeyboardInput(PlayerIndex.One,
                        "Here's your Keyboard", "Type something...",
                        "",
                        new AsyncCallback(GetTypedChars),
                        null);

            base.Update(gameTime);
        }

        private static void GetTypedChars(IAsyncResult asynchronousResult)
        {
            Text = Guide.EndShowKeyboardInput(asynchronousResult);
            Debug.WriteLine(Text);
        }


We modified the update method. Only when the text is empty will the SIP pop-up. The code of the SIP part has been mentioned last time. The last part is to draw the draw function:


protected override void Draw (GameTime gameTime)
         {
             GraphicsDevice.Clear (Color.White);

             // TODO: Add your drawing code here
             spriteBatch.Begin ();

             spriteBatch.DrawString (StartFont, Text, new Vector2 (10, 10), Color.Black);
             //spriteBatch.DrawString(StartFont, "China", new Vector2 (10, 50), Color.Black);
            
             spriteBatch.End ();

             base.Draw (gameTime);
         }


RunProgramFirst, an input method dialog box is implemented. After "Hello, xNa" is entered, the following interface is displayed:






I have noted that I have commented out the drawstring for the second draw "China". What if I did not comment out it? An exception is generated because the characterregion of Sprite font only contains ASCII characters. Therefore, the Chinese font obviously exceeds the character range.





Add Chinese support


Another article on msdn describes this problem:



Http://msdn.microsoft.com/en-us/library/bb447751.aspx



We can use font description processor to add support for specified characters, without the need to expand characterregions, so that many useless characters are added to the font file.



First, find the game project in Solution Explorer. In this example, windowsphonegame1 is displayed. Right-click "add"-"new item" and select "text filepath" with the name messages.txt. Double-click messages.txt to add all Chinese characters to be supported in the game. Because file. readalltext is used, make sure that the text file ends with '\ R' or' \ n.



Next, create a new content processor project, select solution in Solution Explorer, right-click "add"-"New Project", and select "content pipeline extension Library (4.0 )", name it fontprocessor. The modified code in contentprocessor1.cs is as follows:


 
 
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using System.IO;
using System.ComponentModel;

namespace FontProcessor
{
    /// <summary>
    /// This class will be instantiated by the XNA Framework Content Pipeline
    /// to apply custom processing to content data, converting an object of
    /// type TInput to TOutput. The input and output types may be the same if
    /// the processor wishes to alter data without changing its type.
    ///
    /// This should be part of a Content Pipeline Extension Library project.
    ///
    /// TODO: change the ContentProcessor attribute to specify the correct
    /// display name for this processor.
    /// </summary>
    [ContentProcessor(DisplayName = "FontProcessor.ContentProcessor1")]
    public class ContentProcessor1 : FontDescriptionProcessor
    {
        public override SpriteFontContent Process(FontDescription input, ContentProcessorContext context)
        {
            string fullPath = Path.GetFullPath(MessageFile);

            context.AddDependency(fullPath);

            string letters = File.ReadAllText(fullPath, System.Text.Encoding.UTF8);

            foreach (char c in letters)
            {
                input.Characters.Add(c);
            }

            return base.Process(input, context);
        }

        [DefaultValue("messages.txt")]
        [DisplayName("Message File")]
        [Description("The characters in this file will be automatically added to the font.")]
        public string MessageFile
        {
            get { return messageFile; }
            set { messageFile = value; }
        }
        private string messageFile = @"..\WindowsPhoneGame1\messages.txt";
    }
}


First, add two references for reading files:


 




UsingSystem. IO;UsingSystem. componentmodel;


Then add the attributes of messagefile:


  [DefaultValue("messages.txt")]
        [DisplayName("Message File")]
        [Description("The characters in this file will be automatically added to the font.")]
        public string MessageFile
        {
            get { return messageFile; }
            set { messageFile = value; }
        }
        private string messageFile = @"..\WindowsPhoneGame1\messages.txt";


Note the file path. Because the file package is included in the windowsphonegame1 directory and the project is located in the fontprocessor directory, we need to modify the path. Otherwise, a compilation error cannot be found in the file. Because fontprocessor is used during compilation, compile iton is displayed by compilation errors.



We also need to replace the base class contentprocessor of contentprocessor1 with fontdescriptionprocessor. Register content pipeline for messages.txt and add dependencies to inform content pipeline. if messages.txt changes, the font needs to be re-compiled. The last step is to read the file and add the font support for each character. In addition, ensure that your messages.txt file, using the UTF-8 encoding method.



After that, compile fontprocessor first, right-click the references directory of windowsphonegame1content in Solution Explorer, select "Add references", and select fontprocessor on the project tab. Next, in Solution Explorer, right-click Project dependencies and select the checkbox before fontprocessor.



Then, create a new sprite font called yaheifont, named "Microsoft yahei", and select yahei. spritefont, In the content processor item on the property page, switch "Sprite font description-xNa framework" to "fontprocessor. contentprocessor1 ".






Finally, add the font in the game and change the draw function in the game:


protected override void Draw (GameTime gameTime)
         {
             GraphicsDevice.Clear (Color.White);

             // TODO: Add your drawing code here
             spriteBatch.Begin ();

             spriteBatch.DrawString (StartFont, Text, new Vector2 (10, 10), Color.Black);
             spriteBatch.DrawString (YaheiFont, "China", new Vector2 (10, 50), Color.Black);
            
             spriteBatch.End ();

             base.Draw (gameTime);
         }


The final effect is: (assure Chairman Mao that this is not a texture !)





Related Resources


Ma Ning's Windows Phone 7 Development tutorial (1) -- Windows Phone development tool's initial experience



Windows Phone 7 Development tutorial (2)-Windows Phone xNa 4.0 3D Game Development



Windows Phone 7 Development tutorial (3)-use MessageBox and soft keyboard in xNa





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.