Xamarin.MacでCALayerにベジェ曲線を描画する

Xamarin.MacでCALayerにベジェ曲線を描画する方法です。

サンプルプロジェクトはこちら。

NSViewを継承したクラスを作成します。ICALayerDelegateも継承します。

public partial class SampleView : AppKit.NSView, ICALayerDelegate
{
}

CALayerのインスタンス変数を用意して、

private CALayer bgLayer;

コンストラクタが呼ばれたときに、Layer Backed Viewにします。

bgLayer = new CALayer();
this.Layer = bgLayer;
this.WantsLayer = true;
this.LayerContentsRedrawPolicy = NSViewLayerContentsRedrawPolicy.OnSetNeedsDisplay;
this.Layer.Delegate = this;

必要に応じて、Layout()でレイアウトの設定をします。

public override void Layout()
{
    base.Layout();
    this.Layer.Frame = this.Frame;
}

DrawLayer()で描画処理を行います。

[Export("drawLayer:inContext:")]
public void DrawLayer(CALayer layer, CoreGraphics.CGContext context)
{
    NSGraphicsContext.GlobalSaveGraphicsState();
    NSGraphicsContext graphicsContext = NSGraphicsContext.FromGraphicsPort(context, true);
    NSGraphicsContext.CurrentContext = graphicsContext;

    NSBezierPath path = new NSBezierPath();
    //ベジェ曲線
    var x1 = this.Frame.Left;
    var y1 = this.Frame.Top;
    var x2 = this.Frame.Right;
    var y2 = this.Frame.Bottom;
    path.MoveTo(new CoreGraphics.CGPoint(x1, y1));
    path.CurveTo(new CoreGraphics.CGPoint(x2, y1),
                 new CoreGraphics.CGPoint(x1, y2),
                 new CoreGraphics.CGPoint(x2, y2));
    //背景は白
    NSColor.White.Set();
    path.Fill();
    //線は青
    NSColor.Blue.Set();
    //線の太さ
    path.LineWidth = 2;
    path.Stroke();

    NSGraphicsContext.GlobalRestoreGraphicsState();
}

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください