using System.Drawing;
using System;
namespace window
{
    public class QuickCalculateGraphicsPath
    {
        #region パブリックメソッド
        /// <summary>
        /// 指定されたカラーを通過色として GraphicsPath を作成します
        /// アンセーフの実行が許可されている必要があります
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static System.Drawing.Drawing2D.GraphicsPath Calculate(Bitmap bitmap, Color key)
        {
            Color TransparentColor = key;
            System.Drawing.Drawing2D.GraphicsPath graphicsPath =
                new System.Drawing.Drawing2D.GraphicsPath();
            int StartRegionArea = -1;
            Color PixelColor = Color.Empty;
            int width = bitmap.Width;
            int height = bitmap.Height;
            System.Drawing.Imaging.BitmapData bData = bitmap.LockBits(
                new Rectangle(0, 0, width, height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            IntPtr ScanL = bData.Scan0;
            int YOffset = bData.Stride - width * 3;
            unsafe
            {
                byte* p = (byte*)(void*)ScanL;
                for (int y = 0; y <= height - 1; y++)
                {
                    for (int x = 0; x <= width - 1; x++)
                    {
                        int B = (int)p[0];
                        int G = (int)p[1];
                        int R = (int)p[2];
                        PixelColor = Color.FromArgb(R, G, B);
                        if (PixelColor == TransparentColor && StartRegionArea != -1)
                        {
                            graphicsPath.AddRectangle(new Rectangle(StartRegionArea, y, x - StartRegionArea, 1));
                            StartRegionArea = -1;
                        }
                        if (PixelColor != TransparentColor && StartRegionArea == -1)
                        {
                            StartRegionArea = x;
                        }
                        p += 3;
                    }
                    if (StartRegionArea != -1)
                    {
                        graphicsPath.AddRectangle(new Rectangle(StartRegionArea, y, width - StartRegionArea, 1));
                        StartRegionArea = -1;
                    }
                    p += YOffset;
                }
            }
            bitmap.UnlockBits(bData);
            return graphicsPath;
        }
        #endregion
    }
}