我编写了一个简单的类来管理位图的绘制。
这是实现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();
}
似乎是在Win2D之上开始构建抽象的合理方法。
在有Begin/End对的地方,我通常希望看到一些IDisposable的东西,这样你就可以把它和"using"一起使用。类似于:
public void Draw(IDrawingService MyDrawingService)
{
using (var session = MyDrawingService.Begin())
{
_background.Draw(session);
...
}
}
通过这种方式,您可以轻松地从Begin/End对中返回或抛出异常,而不用担心错过End。
我认为这是一个很好的起点。
如果你包装更多的Win2D填充,我可以看到更多的优势,比如说,不用CanvasBitmap,你可以使用自己的Sprite实体。您还可以添加的另一项功能是创建多个精灵批次,而不是使用单个精灵批次。
我即将为一个小项目做一些类似的事情,我会在完成后更新我的版本。