画像をタイル上に並べて描画してみた

画像をタイル上に並べて描画する必要があったのでMonoTouchでコードを書いてみた。
ここでの描画先はCALayer。
アニメーションは必要無かったのでOFFにしてある。

using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;

private CALayer layer;
private CGImage image
private float[] components = new float[]{1.0f};
private CGAffineTransform matrix = new CGAffineTransform (1, 0, 0, 1, 0, 0);

// CGImageを作ったらこのメソッドを呼ぶ
private void Draw()
{
  CATransaction.Begin ();
  CATransaction.AnimationDuration = 0;

  float imageWidth = image.Width;
  float imageHeight = image.Height;
  RectangleF rect = new RectangleF (0, 0, imageWidth, imageHeight);
  using (CGPattern pattern = new CGPattern (rect, matrix, imageWidth, imageHeight, CGPatternTiling.ConstantSpacing, true, DrawTiledImage)) {
    using (CGColorSpace space = CGColorSpace.CreatePattern (null)) {
      using (CGColor color = new CGColor (space, pattern, components)) {
        layer.BackgroundColor = color;
      }
    }
  }

  CATransaction.Commit ();
}

private void DrawTiledImage (CGContext context)
{
  float imageWidth = image.Width;
  float imageHeight = image.Height;
  context.DrawImage (new RectangleF (0, 0, imageWidth, imageHeight), image);
}