using System;
using Chernobyl.Collections.Generic.Event;
using Chernobyl.Graphics.Writing;
using Chernobyl.Readiness;
using Microsoft.Xna.Framework.Graphics;
namespace Chernobyl.Graphics.Xna.Writing
{
///
/// A IFont class that holds an instance to an XNA font known as a
/// SpriteFont.
///
public class XnaFont : IFont
{
///
/// Constructor.
///
/// The instance that
/// takes and gives services.
/// The XNA SpriteFont instance that this
/// XnaFont should represent.
public XnaFont(IEventCollection services, SpriteFont xnaSpriteFont)
{
XnaSpriteFont = xnaSpriteFont;
// by default, if a key is not recognized, then use the question
// mark symbol. We'd prefer not to have exceptions thrown.
XnaSpriteFont.DefaultCharacter = '?';
}
///
/// Measures the text passed in and returns its width and height in pixels.
///
/// The text to measure.
/// The size of the string in pixels.
public Mathematics.Vector2 MeasureString(string text)
{
Mathematics.Vector2 result;
Microsoft.Xna.Framework.Vector2 size = XnaSpriteFont.MeasureString(text);
Utility.ToChernobylVector(out result, ref size);
return result;
}
///
/// True if this instance has been readied, false if otherwise.
///
public bool IsReady
{
get { return _isReady; }
private set
{
bool oldValue = _isReady;
_isReady = value;
if (oldValue == false && _isReady == true && _becameReady != null)
_becameReady(this, EventArgs.Empty);
}
}
///
/// An event that is thrown right after this
/// has been readied. If an event handler is assigned to this event
/// after it has become ready, then that event handler will be
/// immediately invoked.
///
public event EventHandler BecameReady
{
add
{
_becameReady += value;
// if we are already ready, invoke the event
if(IsReady == true)
value(this, EventArgs.Empty);
}
remove { _becameReady -= value; }
}
///
/// The IText instance that is used to control the text created by a
/// graphics API like XNA, OpenGL, DirectX, etc. By default, this
/// property is null for the XnaFont.
///
public IFont Controller { get; protected set; }
///
/// The XNA SpriteFont that is used to represent this font.
///
public SpriteFont XnaSpriteFont
{
get { return _xnaSpriteFont; }
private set
{
SpriteFont oldValue = value;
_xnaSpriteFont = value;
IsReady = (_xnaSpriteFont != null && oldValue == null);
}
}
///
/// The backing field to .
///
bool _isReady;
///
/// The backing method to .
///
EventHandler _becameReady;
///
/// The backing field to .
///
SpriteFont _xnaSpriteFont;
}
}