Xamarin.MacでNSPathをCGPathに変換する
2019年5月22日 (水) 05:13時点におけるimported>Administratorによる版 (Administrator がページ「Xamarin.Mac/NSPathをCGPathに変換する」を「Xamarin.MacでNSPathをCGPathに変換する」に移動しました)
CoreGraphicsのCGPath系にはベジェ曲線を手軽に扱えるクラスがない。 一方でNSPath系にはNSBezierPathというズバリなものがある。 なら変換してしまえばいいんじゃね。
実装
拡張メソッド追加してみた。
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using AppKit;
using CoreGraphics;
public static class NSBezierPathExtensions
{
public static CGPath ToCGPath(this NSBezierPath nsPath)
{
var cgPath = new CGPath();
var points = null as CGPoint[];
for (int i = 0; i < nsPath.ElementCount; i++)
{
var type = nsPath.ElementAt(i, out points);
switch (type)
{
case NSBezierPathElement.MoveTo:
cgPath.MoveToPoint(points[0]);
break;
case NSBezierPathElement.LineTo:
cgPath.AddLineToPoint(points[0]);
break;
case NSBezierPathElement.CurveTo:
cgPath.AddCurveToPoint(cp1: points[0], cp2: points[1], point: points[2]);
break;
case NSBezierPathElement.ClosePath:
cgPath.CloseSubpath();
break;
}
}
return cgPath;
}
}
使い方
線を描いてみた。
public override void DrawRect(CGRect dirtyRect)
{
// 準備
var cg = NSGraphicsContext.CurrentContext.GraphicsPort;
cg.SetFillColor(red: 1.0f, green: 0.0f, blue: 0.0f, alpha: 1.0f);
cg.SetStrokeColor(red: 0.0f, green: 1.0f, blue: 1.0f, alpha: 1.0f);
cg.SetLineWidth(w: 2.0f);
// パス
using (var path = new NSBezierPath())
{
// 形状の始点を設定する
path.MoveTo(new CGPoint(100f, 0f));
// 線を引く
path.LineTo(new CGPoint(200f, 40f));
path.LineTo(new CGPoint(160f, 140f));
path.LineTo(new CGPoint(40f, 140f));
path.LineTo(new CGPoint(0f, 40f));
// 形状を閉じる
path.ClosePath();
// NSPath -> CGPath
// ※ToCGPathは独自の拡張メソッド
cg.AddPath(path.ToCGPath());
}
// 塗りつぶす
cg.FillPath();
}
関連項目
- Xamarin.Mac/CoreGraphicsの基本的な使い方
- Interface Builder/基本的な使い方
- Xamarin.Mac/ウインドウ座標をビュー座標に変換する
- Xamarin.Mac/マウスの中ボタン(ホイール)のクリックを取得する
- Xamarin.Mac/NSViewでドラッグアンドドロップを受け付ける