Xamarin.Mac/NSImageを回転させる

提供: MonoBook
移動: 案内検索

NSImageをサクッと回転させたい。 動くことは動いたが負荷を計測したところ微妙に重いようなので次回はCGImageを回転させてみようと思う。

    using System;
    using AppKit;
    using Foundation;
    using CoreGraphics;
 
    public static class NSImageExtensions
    {
        public static NSImage Rotate(this NSImage nsImage, float degrees)
        {
            degrees = degrees % 360f;
            if (degrees == 0f)
            {// 回転の必要なし
                return nsImage;
            }
 
            CGSize size = nsImage.Size;
            CGSize maxSize;
            if (90f == degrees || 270f == degrees || -90f == degrees || -270f == degrees)
            {
                maxSize = new CGSize(size.Height, size.Width);
            }
            else if (180f == degrees || -180f == degrees)
            {
                maxSize = size;
            }
            else
            {
                maxSize = new CGSize(20 + NMath.Max(size.Width, size.Height), 20 + NMath.Max(size.Width, size.Height));
            }
 
            var rot = new NSAffineTransform();
            rot.RotateByDegrees(degrees);
 
            var center = new NSAffineTransform();
            center.Translate(deltaX: maxSize.Width / 2, deltaY: maxSize.Height / 2);
            rot.AppendTransform(center);
 
            // 新しい画像
            var newImage = new NSImage(maxSize);
 
            // 描画
            newImage.LockFocus();
            rot.Concat();
            var rect = new CGRect(0, 0, size.Width, size.Height);
            var corner = new CGPoint(-size.Width / 2, -size.Height / 2);
            nsImage.Draw(point: corner, fromRect: rect, op: NSCompositingOperation.Copy, delta: 1.0f);
            newImage.UnlockFocus();
 
            return newImage;
        }
    }

関連項目[編集]