我编写了一个简单的类来管理位图的绘制。
这是实现的好方法吗Begin()
-End()
从不同对象绘制多个精灵的方法(如在 XNA 的 omonime 方法中)?
public class Caravaggio : IDrawingService
{
private CanvasDrawingSession _ds = null;
private CanvasSpriteBatch _sb = null;
private CanvasImageInterpolation _interpolation = CanvasImageInterpolation.Linear;
private CanvasSpriteOptions _options = CanvasSpriteOptions.ClampToSourceRect;
private CanvasSpriteSortMode _sortMode = CanvasSpriteSortMode.None;
public bool EnableDebugDrawing { get; set; } = false;
// This is being set from outside each CanvasAnimatedControl Draw event.
// I made this because I'd like to pass only a "Caravaggio" parameter to my draw functions.
public void SetDrawingEntity(CanvasDrawingSession DrawingEntity)
{
_ds = DrawingEntity;
}
public void Begin()
{
_sb = _ds.CreateSpriteBatch(_sortMode, _interpolation, _options);
}
public void End()
{
_sb.Dispose();
_sb = null;
}
public void DrawBitmap(
CanvasBitmap Bitmap,
Rect SourceRect,
Vector2 Position,
Color OverlayColor,
Vector2 Origin,
float Rotation,
Vector2 Scale,
bool FlipHorizontally)
{
if (_ds == null)
{
throw new System.Exception("CanvasDrawingSession not set");
}
if (_sb == null)
{
throw new System.Exception("CanvasSpriteBatch not set. Did you forget to call Begin()?");
}
_sb.DrawFromSpriteSheet(
Bitmap,
Position, SourceRect,
ColorToVector4(OverlayColor),
Origin, Rotation, Scale,
FlipHorizontally ? CanvasSpriteFlip.Horizontal : CanvasSpriteFlip.None);
if (EnableDebugDrawing)
{
_ds.DrawRectangle(Position.X, Position.Y, (float)SourceRect.Width, (float)SourceRect.Height, Colors.Red);
}
}
我知道这很简单,但这只是出于“爱好”的目的。
如果您不想为每个绘制的实体创建一个新的 SpriteBatch 对象,我认为这种方法是一种改进,例如当您以这种方式绘制对象时:
// GameManager
public void Draw(IDrawingService MyDrawingService)
{
MyDrawingService.Begin();
_background.Draw(MyDrawingService);
foreach (Player p in _players)
p.Draw(MyDrawingService);
_score.Draw(MyDrawingService);
MyDrawingService.End();
}