示例#1
0
 /// <summary>
 /// Draw an one-pixel point of fixed color (defined by <see cref="PixelData"/>) in fixed position.
 /// </summary>
 public static void DrawPoint(FastBitmap bmp, int x, int y, PixelData color)
 {
     PixelData* addr = bmp[x, y];
     addr->R = color.R;
     addr->G = color.G;
     addr->B = color.B;
 }
示例#2
0
 public TileBoard()
 {
     this.tileSetData = TileBoard.defaultTileSetData;
     this.tileUnsetData = TileBoard.defaultTileUnsetData;
     this.tileWidth = (int)this.TileSize.Width;
     this.tileHeight = (int)this.TileSize.Height;
 }
示例#3
0
        public static Bitmap GetBitmap(PixelData data, ImageProperties properties)
        {
            float[] values = GetPixels(data, properties);
            byte[] bytes = new byte[values.Length];
            for(int i=0;i<values.Length;i++)
            {
                bytes[i] = properties.WindowAndLevel.GetValue(values[i]);
            }

            //Here create the Bitmap to the know height, width and format
            Bitmap bmp = new Bitmap(properties.Rows, properties.Columns, PixelFormat.Format8bppIndexed);
            bmp.Palette = GetGrayScalePalette();

            //Create a BitmapData and Lock all pixels to be written
            BitmapData bmpData = bmp.LockBits(
                                 new Rectangle(0, 0, bmp.Width, bmp.Height),
                                 ImageLockMode.WriteOnly, bmp.PixelFormat);

            //Copy the data from the byte array into BitmapData.Scan0
            Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);

            //Unlock the pixels
            bmp.UnlockBits(bmpData);

            //Return the bitmap
            return bmp;
        }
示例#4
0
文件: Roi.cs 项目: nhannd/Xian
		/// <summary>
		/// Constructs a new region of interest, specifying an <see cref="IPresentationImage"/> as the source of the pixel data.
		/// </summary>
		/// <param name="presentationImage">The image containing the source pixel data.</param>
		protected Roi(IPresentationImage presentationImage)
		{
			IImageGraphicProvider provider = presentationImage as IImageGraphicProvider;
			if (provider == null)
				return;

			_imageRows = provider.ImageGraphic.Rows;
			_imageColumns = provider.ImageGraphic.Columns;
			_presentationImage = presentationImage;

			_pixelData = provider.ImageGraphic.PixelData;
			if (presentationImage is IModalityLutProvider)
				_modalityLut = ((IModalityLutProvider) presentationImage).ModalityLut;

			if (presentationImage is IImageSopProvider)
			{
				Frame frame = ((IImageSopProvider) presentationImage).Frame;
				_normalizedPixelSpacing = frame.NormalizedPixelSpacing;
				_pixelAspectRatio = frame.PixelAspectRatio;
				_modality = frame.ParentImageSop.Modality;
				_modalityLutUnits = frame.RescaleUnits;
				_subnormalModalityLut = frame.IsSubnormalRescale;
			}
			else
			{
				_normalizedPixelSpacing = new PixelSpacing(0, 0);
				_pixelAspectRatio = new PixelAspectRatio(0, 0);
				_modalityLutUnits = RescaleUnits.None;
				_subnormalModalityLut = false;
			}
		}
示例#5
0
        public void Interpolate(float t, PixelData pd)
        {
            float it;
            if (t > 0)
            {
                it = 1f - t;
            }
            else
            {
                it = t;
                t = 1f - it;
            }

            if (alpha > 0 || pd.alpha > 0)
            {
                this.red = (byte)((this.red * t) + (pd.red * it));
                this.green = (byte)((this.green * t) + (pd.green * it));
                this.blue = (byte)((this.blue * t) + (pd.blue * it));
                this.alpha = (byte)((this.alpha * t) + (pd.alpha * it));
            }
            else
            {
                this.alpha = (byte)((this.alpha * t) + (pd.alpha * it));
            }
        }
示例#6
0
		public void Write(Stream stream, PixelData pixelData, string formatId)
		{
			Bitmap bitmap = null;
			try
			{
				if (pixelData.Width == 0 || pixelData.Height == 0)
				{
					bitmap = new Bitmap(1, 1);
				}
				else
				{
					ColorRgba[] rawColorData = pixelData.Data;
					int[] argbValues = new int[rawColorData.Length];
					unchecked
					{
						for (int i = 0; i < rawColorData.Length; i++)
							argbValues[i] = rawColorData[i].ToIntArgb();
					}

					bitmap = new Bitmap(pixelData.Width, pixelData.Height);
					BitmapData data = bitmap.LockBits(
						new Rectangle(0, 0, bitmap.Width, bitmap.Height),
						ImageLockMode.WriteOnly,
						PixelFormat.Format32bppArgb);
			
					int pixels = data.Width * data.Height;
					Marshal.Copy(argbValues, 0, data.Scan0, pixels);

					bitmap.UnlockBits(data);
				}

				ImageFormat bitmapFormat;
				switch (formatId)
				{
					case ImageCodec.FormatBmp:
						bitmapFormat = ImageFormat.Bmp;
						break;
					case ImageCodec.FormatJpeg:
						bitmapFormat = ImageFormat.Jpeg;
						break;
					case ImageCodec.FormatTiff:
						bitmapFormat = ImageFormat.Tiff;
						break;
					default:
					case ImageCodec.FormatPng:
						bitmapFormat = ImageFormat.Png;
						break;
				}
				bitmap.Save(stream, bitmapFormat);
			}
			finally
			{
				if (bitmap != null)
				{
					bitmap.Dispose();
					bitmap = null;
				}
			}
		}
示例#7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ColorLerpBox"/> class.
 /// </summary>
 /// <param name="parent">Parent control.</param>
 public DrawingArea(Base parent)
     : base(parent)
 {
     SetColor(Color.Black);
     Canvas = new PixelData(16, 16);
     SetSize(128, 128);
     MouseInputEnabled = true;
     m_Depressed = false;
 }
示例#8
0
        public MemImage(int width, int height)
        {
            this.Width = width;
            this.Height = height;

            array = new PixelData[width][];
            for (int i = 0; i < width; i++)
                array[i] = new PixelData[height];
        }
示例#9
0
        public void UseTool(int X, int Y, PixelData Canvas, ref System.Drawing.Color CurrentColor)
        {
            //Canvas[X, Y] = CurrentColor;
            List<Coord> AdjacentCoords = new List<Coord>();
            GetAdjacentCoords(AdjacentCoords, Canvas, new Coord(X, Y), Canvas[X, Y]);

            foreach (Coord coord in AdjacentCoords) {
                Canvas[coord.X, coord.Y] = CurrentColor;
            }
        }
示例#10
0
 private static PixelData LoadPixelData(string filePath)
 {
     PixelData pixelData = new PixelData();
     byte[] imageData = File.ReadAllBytes(filePath);
     using (Stream stream = new MemoryStream(imageData))
     using (Bitmap bitmap = Bitmap.FromStream(stream) as Bitmap)
     {
         pixelData.FromBitmap(bitmap);
     }
     return pixelData;
 }
示例#11
0
    public override void RenderOutput(WebCamScreenController screenController, PixelData pixelData)
    {
        var faceMeshValue = FetchNextIrisTrackingValue();

        RenderAnnotation(screenController, faceMeshValue);

        var texture = screenController.GetScreen();

        texture.SetPixels32(pixelData.Colors);
        texture.Apply();
    }
示例#12
0
        public Bitmap GetBitmapShort(double min, double max, ScaleMap scale)
        {
            short[]    buf     = (short[])DataBuffer;
            double     factor  = max - min;
            int        stride  = AxisSize[0];
            int        page    = AxisSize[0] * AxisSize[1];
            Bitmap     bmp     = new Bitmap(AxisSize[0], AxisSize[1]);
            FastBitmap fastBmp = new FastBitmap(bmp);

            fastBmp.LockBitmap();
            unsafe
            {
                for (int y = 0; y < AxisSize[1]; y++)
                {
                    int        indexY = ((AxisSize[1] - 1) - y);
                    PixelData *pData  = fastBmp[0, y];
                    for (int x = 0; x < AxisSize[0]; x++)
                    {
                        if (color)
                        {
                            int datR = buf[(x + indexY * stride)];
                            int datG = buf[(x + indexY * stride) + page];
                            int datB = buf[(x + indexY * stride) + page * 2];
                            if (ContainsBlanks && (double)datR == BlankValue)
                            {
                                *pData++ = new PixelData(0, 0, 0, 0);
                            }
                            else
                            {
                                int r       = scale.Map(datR);
                                int g       = scale.Map(datG);
                                int b       = scale.Map(datB);
                                *   pData++ = new PixelData(r, g, b, 255);
                            }
                        }
                        else
                        {
                            int dataValue = buf[x + indexY * stride];
                            if (ContainsBlanks && (double)dataValue == BlankValue)
                            {
                                *pData++ = new PixelData(0, 0, 0, 0);
                            }
                            else
                            {
                                Byte val     = scale.Map(dataValue);
                                *    pData++ = new PixelData(val, val, val, 255);
                            }
                        }
                    }
                }
            }
            fastBmp.UnlockBitmap();
            return(bmp);
        }
示例#13
0
    public override void RenderOutput(WebCamScreenController screenController, PixelData pixelData)
    {
        var detections = FetchNextFaceDetectionsPresence() ? FetchNextFaceDetections() : new List <Detection>();

        RenderAnnotation(screenController, detections);

        var texture = screenController.GetScreen();

        texture.SetPixels32(pixelData.Colors);
        texture.Apply();
    }
示例#14
0
        public override void GetData(object target, Stream outgoingData)
        {
            RenderTarget renderTarget = target as RenderTarget;
            PixelData    layer        = renderTarget.GetPixelData();
            Bitmap       bitmap       = layer.ToBitmap();

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(outgoingData, renderTarget.ToString());
            formatter.Serialize(outgoingData, bitmap);
            outgoingData.Flush();
        }
示例#15
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Creates a new <code>PixelData</code> instance from an existing instance.
 /// The pixel information is completely copied and no link between the two
 /// instance will maintained.
 /// </summary>
 /// <param name="pixel">A <code>PixelData</code> instance.</param>
 public PixelData(PixelData pixel)
 {
     if (pixel == null)
       {
     throw new ArgumentException("Unable to clone a null instance of PixelData.");
       }
       X = pixel.X;
       Y = pixel.Y;
       R = pixel.R;
       G = pixel.G;
       B = pixel.B;
 }
示例#16
0
        private Texture LoadStageFillingTexture(string filepath)
        {
            Size2D      dimensions = new Size2D(Window.Instance.WindowSize.Width, Window.Instance.WindowSize.Height);
            PixelBuffer pb         = ImageLoading.LoadImageFromFile(filepath, dimensions, FittingModeType.ScaleToFill);
            PixelData   pd         = PixelBuffer.Convert(pb);

            Texture texture = new Texture(TextureType.TEXTURE_2D, pd.GetPixelFormat(), pd.GetWidth(), pd.GetHeight());

            texture.Upload(pd);

            return(texture);
        }
示例#17
0
        private void CreateReferenceImage(string name, int width, int height, Action <Canvas> renderMethod)
        {
            PixelData image = this.RenderToTexture(width, height, renderMethod);

            string      formatId = ImageCodec.FormatPng;
            IImageCodec codec    = ImageCodec.GetWrite(formatId);

            using (Stream stream = File.Open(TestHelper.GetEmbeddedResourcePath(name, ".png"), FileMode.Create))
            {
                codec.Write(stream, image, formatId);
            }
        }
示例#18
0
        private PixelData LoadPixelData(string filePath)
        {
            PixelData pixelData = new PixelData();

            byte[] imageData = File.ReadAllBytes(filePath);
            using (Stream stream = new MemoryStream(imageData))
                using (Bitmap bitmap = Bitmap.FromStream(stream) as Bitmap)
                {
                    pixelData.FromBitmap(bitmap);
                }
            return(pixelData);
        }
示例#19
0
        public override void GetData(object target, Stream outgoingData)
        {
            Texture   texture = target as Texture;
            PixelData layer   = texture.GetPixelData();
            Bitmap    bitmap  = layer.ToBitmap();

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(outgoingData, texture.ToString());
            formatter.Serialize(outgoingData, bitmap);
            outgoingData.Flush();
        }
示例#20
0
        public Color UpdateColorAndDirection(Color currentColor)
        {
            if (currentColor.ToArgb() == Color.ToArgb())
            {
                ModifiedPixel = new PixelData(PositionX, PositionY, Color.White);
                TurnLeft();
                return Color.White;
            }

            ModifiedPixel = new PixelData(PositionX, PositionY, Color);
            TurnRight();
            return Color;
        }
示例#21
0
        private void GetAdjacentCoords(List<Coord> AdjacentCoords, PixelData Canvas, Coord coord, System.Drawing.Color SeekColor)
        {
            if (coord.X >= 0 && coord.X < Canvas.Width && coord.Y >= 0 && coord.Y < Canvas.Height && Canvas[coord.X, coord.Y] == SeekColor) {
                if (!AdjacentCoords.Contains(coord)) {
                    AdjacentCoords.Add(coord);

                    GetAdjacentCoords(AdjacentCoords, Canvas, new Coord(coord.X - 1, coord.Y), SeekColor);
                    GetAdjacentCoords(AdjacentCoords, Canvas, new Coord(coord.X + 1, coord.Y), SeekColor);
                    GetAdjacentCoords(AdjacentCoords, Canvas, new Coord(coord.X, coord.Y - 1), SeekColor);
                    GetAdjacentCoords(AdjacentCoords, Canvas, new Coord(coord.X, coord.Y + 1), SeekColor);
                }
            }
        }
示例#22
0
        private static void SetBitmap(Bitmap bitmap, PixelData pixelData)
        {
            var bmd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);

            try
            {
                Marshal.Copy(pixelData.Pixels, 0, bmd.Scan0, pixelData.Pixels.Length);
            }
            finally
            {
                bitmap.UnlockBits(bmd);
            }
        }
示例#23
0
        private void TestImagesEqual(Bitmap referenceImage, Action <Canvas> renderMethod)
        {
            PixelData image     = this.RenderToTexture(referenceImage.Width, referenceImage.Height, renderMethod);
            PixelData reference = BitmapToPixelData(referenceImage);
            bool      equal     = this.AreImagesEqual(reference, image);

            if (!equal && Debugger.IsAttached)
            {
                // If the debugger is attached, create a nice diff image for the programmer to view.
                PixelData diff = this.CreateDiffImage(image, reference);
            }
            Assert.IsTrue(equal);
        }
示例#24
0
 public static int[] GetPixelDataIntArgb(this PixelData pixelData)
 {
     ColorRgba[] rawData    = pixelData.Data;
     int[]       argbValues = new int[rawData.Length];
     unchecked
     {
         for (int i = 0; i < rawData.Length; i++)
         {
             argbValues[i] = rawData[i].ToIntArgb();
         }
     }
     return(argbValues);
 }
示例#25
0
        public static unsafe List <Spot> ImageList(ImageData source, ImageData search, byte variation = 0, MatchMode mode = MatchMode.TopLeft)
        {
            List <Spot> list = new List <Spot>();

            fixed(byte *src = source.RawData)
            {
                fixed(byte *sec = search.RawData)
                {
                    for (int y = 0; y < source.Height - search.Height; y++)
                    {
                        for (int x = 0; x < source.Width - search.Width; x++)
                        {
                            for (int smally = 0; smally < search.Height; smally++)
                            {
                                for (int smallx = 0; smallx < search.Width; smallx++)
                                {
                                    PixelData sourcePixel = *(PixelData *)(src + ((y + smally) * source.Stride + (x + smallx) * 3));
                                    PixelData searchPixel = *(PixelData *)(sec + smally * search.Stride + smallx * 3);

                                    if ((searchPixel.R < sourcePixel.R - variation || searchPixel.R > sourcePixel.R + variation) || (searchPixel.G < sourcePixel.G - variation || searchPixel.G > sourcePixel.G + variation) || (searchPixel.B < sourcePixel.B - variation || searchPixel.B > sourcePixel.B + variation))
                                    {
                                        goto SecondLoop;
                                    }
                                }
                            }

                            switch (mode)
                            {
                            case MatchMode.BottomLeft: list.Add(new Spot(x, y + search.Height)); break;

                            case MatchMode.BottomRight: list.Add(new Spot(x + search.Width, y + search.Height)); break;

                            case MatchMode.Mid: list.Add(new Spot(x + search.Mid.X, y + search.Mid.Y)); break;

                            case MatchMode.TopLeft: list.Add(new Spot(x, y)); break;

                            case MatchMode.TopRight: list.Add(new Spot(x + search.Width, y)); break;

                            case MatchMode.None: list.Add(new Spot(x, y)); break;

                            default: list.Add(new Spot(x, y)); break;
                            }

                            SecondLoop :;
                        }
                    }

                    return(list);
                }
            }
        }
示例#26
0
        public void Iterate()
        {
            _colourClusterAllocation    = new Hashtable(); //for keeping track of colour<->cluster allocation
            _pixelDataClusterAllocation = new Hashtable();
            _clusterColours             = new Hashtable();

            UnsafeBitmap fastBitmap = new UnsafeBitmap(_image);

            fastBitmap.LockBitmap();
            Point size = fastBitmap.Size;
            BGRA *pPixel;

            for (int y = 0; y < size.Y; y++)
            {
                pPixel = fastBitmap[0, y];
                for (int x = 0; x < size.X; x++)
                {
                    PixelData pd = Colour.GetPixelData(pPixel, _model);
                    AllocateToCluster(pd);
                    //increment the pointer
                    pPixel++;
                }
            }
            fastBitmap.UnlockBitmap();

            CalculateClusterCentroids();

            _processedImage = (Bitmap)_image.Clone();

            //segment the image based on the cluster
            fastBitmap = new UnsafeBitmap(_processedImage);
            fastBitmap.LockBitmap();
            for (int y = 0; y < size.Y; y++)
            {
                pPixel = fastBitmap[0, y];
                for (int x = 0; x < size.X; x++)
                {
                    PixelData pd     = Colour.GetPixelData(pPixel, _model);
                    Color     newClr = (Color)_clusterColours[pd.Name];
                    pPixel->red   = newClr.R;
                    pPixel->green = newClr.G;
                    pPixel->blue  = newClr.B;
                    //increment the pointer
                    pPixel++;
                }
            }

            fastBitmap.UnlockBitmap();

            CheckConvergence();
        }
示例#27
0
    public void LoadColorPalette()
    {
        pixelData = new PixelData(platformImage);

        pixelData.LoadPixelColors();
        ColorTile temp = new ColorTile();

        foreach (var pix in pixelData.imageColorList)
        {
            temp.colorHex = ColorUtility.ToHtmlStringRGBA(pix).ToString();
            temp.colorVal = pix;
            colorTiles.Add(temp);
        }
    }
示例#28
0
        /// <summary>
        /// Create a new strip of count neopixels
        /// </summary>
        public NeoPixelStrip(int count)
        {
            data = new PixelData();
            var settings = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 2_400_000,
                Mode           = SpiMode.Mode0,
                DataBitLength  = 8
            };

            device = SpiDevice.Create(settings);
            pixels = new List <NeoPixel>();
            Count  = count;
        }
示例#29
0
        /// <summary>
        /// Used for serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Width", Width);
            info.AddValue("Height", Height);
            info.AddValue("BitsPerPixel", BitsPerPixel);
            info.AddValue("PixelType", PixelType);
            info.AddValue("PlaneSizes", PlaneSizes);
            info.AddValue("Pitches", Pitches);
            info.AddValue("Lines", Lines);
            info.AddValue("NumberOfPlanes", NumberOfPlanes);
            PixelData px = new PixelData(this.PlaneSizes, this.Planes);

            info.AddValue("PixelData", px.Save());
        }
示例#30
0
        private void DrawToLineDrawingImage(IBImage trg, double r, PixelData color)
        {
            double _x = curCoord.x - trg.Rect.OffsetX, _y = curCoord.y - trg.Rect.OffsetY;

            if (_x < 0 || _y < 0 || _x >= trg.imageData.actualSize.Width || _y >= trg.imageData.actualSize.Height)
            {
                return;
            }

            double preX = histCoord[1].x - trg.Rect.OffsetX, preY = histCoord[1].y - trg.Rect.OffsetY, prePre = histPressure[1];
            double dx = curCoord.x - histCoord[1].x, dy = curCoord.y - histCoord[1].y, dp = curPressure - prePre;
            double length = Math.Sqrt(dx * dx + dy * dy);

            if (length > 200)
            {
                return;
            }
            double interval = 0.1 / length;
            double t        = last_t / length;

            while (t < 1.0)
            {
                double x = preX + dx * t;
                double y = preY + dy * t;

                double p = prePre + dp * t;

                if (p == 0)
                {
                    DrawCircle(trg, x, y, r, color);
                }
                else if (p > 0.2)
                {
                    double _r = r;
                    if (p != 0.0)
                    {
                        _r *= PenTouch(p);
                    }

                    DrawCircle(trg, x, y, _r, color);
                }

                t += r * interval;
            }

            last_t = length * (t - 1.0);


            EntryTexUpdate(trg.imageData);
        }
示例#31
0
        public PixelData GetPixelData()
        {
            ColorRgba[] colors = new ColorRgba[Data.Length / 4];
            for (int i = 0, j = 0; i < Data.Length; i += 4, j += 1)
            {
                colors[j] = new ColorRgba(Data[i], Data[i + 1], Data[i + 2], Data[i + 3]);
            }

            PixelData pixelData = new PixelData();

            pixelData.SetData(colors, Width, Height);
            pixelData.ColorTransparentPixels();
            return(pixelData);
        }
示例#32
0
 public void SetFormat(BitmapFormat format)
 {
     if (m_data == default(PixelData))
     {
         m_format = format;
         m_data   = new PixelData(m_format.ImageSize);
         m_pData  = GCHandle.Alloc(m_data, GCHandleType.Pinned);
         InitMedia();
     }
     else
     {
         throw new InvalidOperationException("Bitmap format already set");
     }
 }
示例#33
0
        public static Bitmap ToBitmap(this PixelData target)
        {
            var bitmap = new Bitmap(target.Width, target.Height, PixelFormat.Format32bppArgb);

            bitmap.SetResolution(96, 96);

            var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            Marshal.Copy(target.Pixels, 0, bitmapData.Scan0, target.Pixels.Length);

            bitmap.UnlockBits(bitmapData);

            return(bitmap);
        }
示例#34
0
 /// <summary>
 /// Determines whether the specified pixel data block is completely transparent in
 /// the specified area.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="pos"></param>
 /// <param name="size"></param>
 private static bool IsCompletelyTransparent(PixelData data, Point2 pos, Point2 size)
 {
     for (int y = pos.Y; y < pos.Y + size.Y; y++)
     {
         for (int x = pos.X; x < pos.X + size.X; x++)
         {
             if (data[x, y].A > 0)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
示例#35
0
        public static unsafe Spot ImageArea(ImageData source, ImageData search, Boundary bounds, byte variation = 0, MatchMode mode = MatchMode.TopLeft)
        {
            fixed(byte *src = source.RawData)
            {
                fixed(byte *sec = search.RawData)
                {
                    for (int y = bounds.Top; y < bounds.Bottom - search.Height; y++)
                    {
                        for (int x = bounds.Left; x < bounds.Right - search.Width; x++)
                        {
                            for (int smally = 0; smally < search.Height; smally++)
                            {
                                for (int smallx = 0; smallx < search.Width; smallx++)
                                {
                                    PixelData sourcePixel = *(PixelData *)(src + ((y + smally) * source.Stride + (x + smallx) * 3));
                                    PixelData searchPixel = *(PixelData *)(sec + smally * search.Stride + smallx * 3);

                                    if ((searchPixel.R < sourcePixel.R - variation || searchPixel.R > sourcePixel.R + variation) || (searchPixel.G < sourcePixel.G - variation || searchPixel.G > sourcePixel.G + variation) || (searchPixel.B < sourcePixel.B - variation || searchPixel.B > sourcePixel.B + variation))
                                    {
                                        goto SecondLoop;
                                    }
                                }
                            }

                            switch (mode)
                            {
                            case MatchMode.BottomLeft: return(new Spot(x, y + search.Height));

                            case MatchMode.BottomRight: return(new Spot(x + search.Width, y + search.Height));

                            case MatchMode.Mid: return(new Spot(x + search.Mid.X, y + search.Mid.Y));

                            case MatchMode.TopLeft: return(new Spot(x, y));

                            case MatchMode.TopRight: return(new Spot(x + search.Width, y));

                            case MatchMode.None: return(new Spot(x, y));

                            default: return(new Spot(x, y));
                            }

                            SecondLoop :;
                        }
                    }

                    return(Spot.Empty);
                }
            }
        }
示例#36
0
        public static Bitmap ToBitmap(PixelData pixelData)
        {
            var bitmap     = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            var bitmapdata = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            try
            {
                Marshal.Copy(pixelData.Pixels, 0, bitmapdata.Scan0, pixelData.Pixels.Length);
            }
            finally
            {
                bitmap.UnlockBits(bitmapdata);
            }
            return(bitmap);
        }
示例#37
0
        public void PixelDataConstructor()
        {
            tlog.Debug(tag, $"PixelDataConstructor START");

            byte[] buffer = new byte[1024];

            var testingTarget = new PixelData(buffer, 1024, 100, 150, PixelFormat.L8, PixelData.ReleaseFunction.Free);

            Assert.IsNotNull(testingTarget, "Can't create success object PixelData");
            Assert.IsInstanceOf <PixelData>(testingTarget, "Should be an instance of PixelData type.");

            buffer = null;
            testingTarget.Dispose();
            tlog.Debug(tag, $"PixelDataConstructor END (OK)");
        }
示例#38
0
        /// <summary>
        /// Constructor used for deserialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public PlanarImage(SerializationInfo info, StreamingContext context)
        {
            Width        = info.GetInt32("Width");
            Height       = info.GetInt32("Height");
            BitsPerPixel = info.GetInt32("BitsPerPixel");
            PixelType    = (PixelAlignmentType)info.GetValue("PixelType", typeof(PixelAlignmentType));
            PlaneSizes   = (int[])info.GetValue("PlaneSizes", typeof(int[]));
            Pitches      = (int[])info.GetValue("Pitches", typeof(int[]));
            Lines        = (int[])info.GetValue("Lines", typeof(int[]));
            byte[] pixelData = (byte[])info.GetValue("PixelData", typeof(byte[]));
            NumberOfPlanes = info.GetInt32("NumberOfPlanes");
            PixelData px = new PixelData(PlaneSizes, pixelData);

            Planes = px.Load();
        }
示例#39
0
 public static PixelData GetLumpPixelData(PixelData pixels, int range = 10)
 {
     Color[,] colors = pixels.GetColorsClone();
     for (var i = 0; i <= pixels.Width - 1; i++)
     {
         for (var j = 0; j <= pixels.Height - 1; j++)
         {
             var r = (colors[i, j].R / range) * range;
             var g = (colors[i, j].G / range) * range;
             var b = (colors[i, j].B / range) * range;
             colors[i, j] = Color.FromArgb(r, g, b);
         }
     }
     return(PixelData.CreateFromColors(colors));
 }
示例#40
0
        public unsafe override void Filter(int x, int y, PixelGet getPixel, PixelData *pPixel, int x0, int y0, int x1, int y1)
        {
            PixelData pixel1 = new PixelData();
            PixelData pixel2 = new PixelData();

            this.Matrix = mat1;
            this.applyConvolution3x3(x, y, getPixel, &pixel1);

            this.Matrix = mat2;
            this.applyConvolution3x3(x, y, getPixel, &pixel2);

            pPixel->red   = (byte)Math.Sqrt(pixel1.red * pixel1.red + pixel2.red * pixel2.red);
            pPixel->green = (byte)Math.Sqrt(pixel1.green * pixel1.green + pixel2.green * pixel2.green);
            pPixel->blue  = (byte)Math.Sqrt(pixel1.blue * pixel1.blue + pixel2.blue * pixel2.blue);
        }
示例#41
0
        /// <summary>
        /// 返回指定位图包含的像素数据
        /// </summary>
        public static PixelData GetPixelDataFromBitmap(Bitmap bmp)
        {
            Color[,] colors = new Color[bmp.Width - 1 + 1, bmp.Height - 1 + 1];
            var loopTo = bmp.Width - 1;

            for (var i = 0; i <= loopTo; i++)
            {
                var loopTo1 = bmp.Height - 1;
                for (var j = 0; j <= loopTo1; j++)
                {
                    colors[i, j] = bmp.GetPixel(i, j);
                }
            }
            return(PixelData.CreateFromColors(colors));
        }
示例#42
0
        /// <summary>
        /// Retrieves the rasterized <see cref="Duality.Drawing.PixelData"/> for a single glyph.
        /// </summary>
        /// <param name="glyph">The glyph of which to retrieve the Bitmap.</param>
        /// <returns>The Bitmap that has been retrieved, or null if the glyph is not supported.</returns>
        public PixelData GetGlyphBitmap(char glyph)
        {
            Rect targetRect;
            int  charIndex = (int)glyph > this.charLookup.Length ? 0 : this.charLookup[(int)glyph];

            this.pixelData.LookupAtlas(charIndex, out targetRect);
            PixelData subImg = new PixelData(
                MathF.RoundToInt(targetRect.W),
                MathF.RoundToInt(targetRect.H));

            this.pixelData.MainLayer.DrawOnto(subImg, BlendMode.Solid,
                                              -MathF.RoundToInt(targetRect.X),
                                              -MathF.RoundToInt(targetRect.Y));
            return(subImg);
        }
        private static float ImageKernelFunction3X3(PixelData pd, int x, int y)
        {
            float weightedMean = 0;

            weightedMean += 0.0625f * pd.GetPixel(x - 1, y - 1);
            weightedMean += 0.0625f * pd.GetPixel(x - 1, y + 0);
            weightedMean += 0.0625f * pd.GetPixel(x - 1, y + 1);
            weightedMean += 0.0625f * pd.GetPixel(x + 0, y - 1);
            weightedMean += 0.5000f * pd.GetPixel(x + 0, y + 0);
            weightedMean += 0.0625f * pd.GetPixel(x + 0, y + 1);
            weightedMean += 0.0625f * pd.GetPixel(x + 1, y - 1);
            weightedMean += 0.0625f * pd.GetPixel(x + 1, y + 0);
            weightedMean += 0.0625f * pd.GetPixel(x + 1, y + 1);
            return(weightedMean);
        }
示例#44
0
        static TileBoard()
        {
            TileBoard.defaultTileSetData = TileBoardBase.DefaultTileSetImage.GetPixelData();
            TileBoard.defaultTileUnsetData = TileBoardBase.DefaultTileUnsetImage.GetPixelData();

            TileBoard.tileTypeImageData = new Dictionary<TileType, PixelData>();
            var imageFormat = TileBoardBase.DefaultTileUnsetImage.Format;

            foreach (var keyPair in TileBoardBase.TileTypeImages)
            {
                TileBoard.tileTypeImageData.Add(
                    keyPair.Key,
                    keyPair.Value.ConvertFormat(PixelFormats.Bgra32).GetPixelData(TileBoard.defaultTileUnsetData.Stride));
            }

            TileBoard.flagImageData = TileBoardBase.FlagImage.GetPixelData(TileBoard.defaultTileUnsetData.Stride);
            TileBoard.questionMarkImageData = TileBoardBase.QuestionMarkImage.GetPixelData(TileBoard.defaultTileUnsetData.Stride);
        }
示例#45
0
 public static PixelData GetPixelData(int R, int G, int B, Types model)
 {
     Color clr = Color.FromArgb(R, G, B);
     PixelData pd = new PixelData(0, 0, 0, clr.Name);
     switch (model)
     {
         case Types.RGB:
             pd.Ch1 = R;
             pd.Ch2 = G;
             pd.Ch3 = B;
             break;
         case Types.HSV:
             pd = RGBToHSV(R, G, B);
             break;
         default:
             throw new Exception("Conversion not implemented");
     }
     pd.Name = clr.Name;
     return pd;
 }
示例#46
0
 public static PixelData GetPixelData(BGRA* pixel, Types model)
 {
     Color clr = Color.FromArgb(pixel->red, pixel->green, pixel->blue);
     PixelData pd = new PixelData(0, 0, 0, clr.Name);
     switch (model)
     {
         case Types.RGB:
             pd.Ch1 = pixel->red;
             pd.Ch2 = pixel->green;
             pd.Ch3 = pixel->blue;
             break;
         case Types.HSV:
             pd = RGBToHSV(pixel);
             break;
         default:
             throw new Exception("Conversion not implemented");
     }
     pd.Name = clr.Name;
     return pd;
 }
示例#47
0
        public PixelData GetPixel(int x, int y)
        {
            if (isLocked)
            {
                PixelData returnValue = *PixelAt(x, y);
                return returnValue;
            }
            else
            {
                Color c = bitmap.GetPixel(x, y);
                PixelData data = new PixelData()
                {
                    R = c.R,
                    G = c.G,
                    B = c.B
                };
                return data;

            }
        }
示例#48
0
		public PixelData Read(Stream stream)
		{
			ColorRgba[] rawColorData;
			int width;
			int height;
			PixelData pixelData = new PixelData();

			using (Bitmap bitmap = Bitmap.FromStream(stream) as Bitmap)
			{
				// Retrieve data
				BitmapData bitmapData = bitmap.LockBits(
					new Rectangle(0, 0, bitmap.Width, bitmap.Height),
					ImageLockMode.ReadOnly,
					PixelFormat.Format32bppArgb);
			
				int pixelCount = bitmapData.Width * bitmapData.Height;
				int[] argbValues = new int[pixelCount];
				Marshal.Copy(bitmapData.Scan0, argbValues, 0, pixelCount);
				bitmap.UnlockBits(bitmapData);
				
				width = bitmapData.Width;
				height = bitmapData.Height;
				rawColorData = new ColorRgba[width * height];
				Parallel.ForEach(Partitioner.Create(0, rawColorData.Length), range =>
				{
					for (int i = range.Item1; i < range.Item2; i++)
					{
						rawColorData[i].A = (byte)((argbValues[i] & 0xFF000000) >> 24);
						rawColorData[i].R = (byte)((argbValues[i] & 0x00FF0000) >> 16);
						rawColorData[i].G = (byte)((argbValues[i] & 0x0000FF00) >> 8);
						rawColorData[i].B = (byte)((argbValues[i] & 0x000000FF) >> 0);
					}
				});
			}

			pixelData.SetData(rawColorData, width, height);
			pixelData.ColorTransparentPixels();

			return pixelData;
		}
示例#49
0
    public PixelBuffer(int width, int height)
    {
        // Create a MemoryDC to hold the bitmap.  Use IntPtr.Zero 
        // to create a device context that is compatible with the screen.
        
        fMemoryDC = GDI32.CreateCompatibleDC(IntPtr.Zero);


        // Create a bitmap compatible with the screen
        fBitmapInfo = new BITMAPINFO();
        fBitmapInfo.Init();


        fBitmapInfo.bmiHeader.biWidth = width;
        fBitmapInfo.bmiHeader.biHeight = -height;
        fBitmapInfo.bmiHeader.biPlanes = 1;
        fBitmapInfo.bmiHeader.biBitCount = 32;
        fBitmapInfo.bmiHeader.biClrImportant = 0;
        fBitmapInfo.bmiHeader.biClrUsed = 0;
        fBitmapInfo.bmiHeader.biCompression = GDI32.BI_RGB;
        fBitmapInfo.bmiColors = IntPtr.Zero;
        
        fBitmapHandle = GDI32.CreateDIBSection(User32.GetDC(IntPtr.Zero),
            ref fBitmapInfo, GDI32.DIB_RGB_COLORS, ref fBits, IntPtr.Zero, 0);

        fPixelData = new PixelData(width, height, 32, width * 4, fBits);

        // Get the bitmap structure back out so we can 
        // get our hands on the created pointer and whatnot
        //GDI32.GetBitmap(fBitmapHandle, ref fBitmapStructure);
        //fBits = fBitmapStructure.bmBits;

        // Select the bitmap into the memoryDC
        fOldBitmapHandle = GDI32.SelectObject(fMemoryDC, fBitmapHandle);
        fAlpha = 255;
    }
示例#50
0
        public static PixelData overlayPixelData(PixelData over, PixelData under)
        {
            if (over.alpha == 255 || under.alpha == 0)
                return over;
            if (over.alpha == 0)
                return under;

            int num1 = (int)over.alpha;
            int num2 = ((255 - num1) * (int)under.alpha + 127) / 255;
            int num3 = num1 + num2;
            int num4 = num3 / 2;
            PixelData pixelData;
            pixelData.blue = (byte)(((int)over.blue * num1 + (int)under.blue * num2 + num4) / num3);
            pixelData.green = (byte)(((int)over.green * num1 + (int)under.green * num2 + num4) / num3);
            pixelData.red = (byte)(((int)over.red * num1 + (int)under.red * num2 + num4) / num3);
            pixelData.alpha = (byte)num3;
            return pixelData;
        }
示例#51
0
 public void SetPixel(int x, int y, PixelData colour)
 {
     if (isLocked)
     {
         PixelData* pixel = PixelAt(x, y);
         *pixel = colour;
     }
     else
     {
         Color c = Color.FromArgb(colour.R, colour.G, colour.B);
         bitmap.SetPixel(x, y, c);
     }
 }
示例#52
0
		private static void Signed5Bit(byte[] pixelData, PixelData pixelDataWrapper)
		{
			pixelData[0] = 31;

			int actualValue = pixelDataWrapper.GetPixel(0, 0);

			Assert.AreEqual(-1, actualValue);

			int expectedValue = -1;
			pixelDataWrapper.SetPixel(0, 0, expectedValue);
			actualValue = pixelDataWrapper.GetPixel(0, 0);
			Assert.AreEqual(expectedValue, actualValue);

			expectedValue = -16;
			pixelDataWrapper.SetPixel(0, 0, expectedValue);
			actualValue = pixelDataWrapper.GetPixel(0, 0);
			Assert.AreEqual(expectedValue, actualValue);

			expectedValue = 15;
			pixelDataWrapper.SetPixel(0, 0, expectedValue);
			actualValue = pixelDataWrapper.GetPixel(0, 0);
			Assert.AreEqual(expectedValue, actualValue);

			expectedValue = 0;
			pixelDataWrapper.SetPixel(0, 0, expectedValue);
			actualValue = pixelDataWrapper.GetPixel(0, 0);
			Assert.AreEqual(expectedValue, actualValue);
		}
示例#53
0
        private void AllocateToCluster(PixelData pd)
        {
            //find distance of this colour from each cluster centroid
            Dictionary<string, Distance> distances = new Dictionary<string, Distance>();

            foreach (KeyValuePair<string, Cluster> c in _currentCluster)
            {
                float d = (float)Math.Sqrt(
                    (double)Math.Pow((c.Value.CentroidR - pd.Ch1), 2) +
                    (double)Math.Pow((c.Value.CentroidG - pd.Ch2), 2) +
                    (double)Math.Pow((c.Value.CentroidB - pd.Ch3), 2)
                );
                distances.Add(c.Key, new Distance(d));
            }

            //allocate this colour to the closest cluster based on distance
            List<KeyValuePair<string, Distance>> list = new List<KeyValuePair<string, Distance>>();
            list.AddRange(distances);

            list.Sort(delegate(KeyValuePair<string, Distance> kvp1, KeyValuePair<string, Distance> kvp2)
            { return Comparer<float>.Default.Compare(kvp1.Value.Measure, kvp2.Value.Measure); });

            //assign to closest cluster
            if (_pixelDataClusterAllocation.ContainsKey(list[0].Key))
            {
                ((List<PixelData>)_pixelDataClusterAllocation[list[0].Key]).Add(pd);
            }
            else
            {
                List<PixelData> clrList = new List<PixelData>();
                clrList.Add(pd);
                _pixelDataClusterAllocation.Add(list[0].Key, clrList);
            }
        }
示例#54
0
		private static float ImageKernelFunction3X3(PixelData pd, int x, int y)
		{
			float weightedMean = 0;
			weightedMean += 0.0625f*pd.GetPixel(x - 1, y - 1);
			weightedMean += 0.0625f*pd.GetPixel(x - 1, y + 0);
			weightedMean += 0.0625f*pd.GetPixel(x - 1, y + 1);
			weightedMean += 0.0625f*pd.GetPixel(x + 0, y - 1);
			weightedMean += 0.5000f*pd.GetPixel(x + 0, y + 0);
			weightedMean += 0.0625f*pd.GetPixel(x + 0, y + 1);
			weightedMean += 0.0625f*pd.GetPixel(x + 1, y - 1);
			weightedMean += 0.0625f*pd.GetPixel(x + 1, y + 0);
			weightedMean += 0.0625f*pd.GetPixel(x + 1, y + 1);
			return weightedMean;
		}
示例#55
0
        private static void DrawTileHighlights(Canvas canvas, ICmpTilemapRenderer renderer, Point2 origin, IReadOnlyGrid<bool> highlight, ColorRgba fillTint, ColorRgba outlineTint, TileHighlightMode mode, List<Vector2[]> outlineCache = null)
        {
            if (highlight.Width == 0 || highlight.Height == 0) return;

            // Generate strippled line texture if not available yet
            if (strippledLineTex == null)
            {
                PixelData pixels = new PixelData(8, 1);
                for (int i = 0; i < pixels.Width / 2; i++)
                    pixels[i, 0] = ColorRgba.White;
                for (int i = pixels.Width / 2; i < pixels.Width; i++)
                    pixels[i, 0] = ColorRgba.TransparentWhite;

                using (Pixmap pixmap = new Pixmap(pixels))
                {
                    strippledLineTex = new Texture(pixmap,
                        TextureSizeMode.Default,
                        TextureMagFilter.Nearest,
                        TextureMinFilter.Nearest,
                        TextureWrapMode.Repeat,
                        TextureWrapMode.Repeat,
                        TexturePixelFormat.Rgba);
                }
            }

            BatchInfo defaultMaterial = new BatchInfo(DrawTechnique.Alpha, canvas.State.Material.MainColor);
            BatchInfo strippleMaterial = new BatchInfo(DrawTechnique.Alpha, canvas.State.Material.MainColor, strippledLineTex);
            bool uncertain = (mode & TileHighlightMode.Uncertain) != 0;
            bool selection = (mode & TileHighlightMode.Selection) != 0;

            Component component = renderer as Component;
            Transform transform = component.GameObj.Transform;
            Tilemap tilemap = renderer.ActiveTilemap;
            Tileset tileset = tilemap != null ? tilemap.Tileset.Res : null;
            Vector2 tileSize = tileset != null ? tileset.TileSize : Tileset.DefaultTileSize;
            Rect localRect = renderer.LocalTilemapRect;

            // Determine the object's local coordinate system (rotated, scaled) in world space
            Vector2 worldAxisX = Vector2.UnitX;
            Vector2 worldAxisY = Vector2.UnitY;
            MathF.TransformCoord(ref worldAxisX.X, ref worldAxisX.Y, transform.Angle, transform.Scale);
            MathF.TransformCoord(ref worldAxisY.X, ref worldAxisY.Y, transform.Angle, transform.Scale);

            Vector2 localOriginPos = tileSize * origin;
            Vector2 worldOriginPos = localOriginPos.X * worldAxisX + localOriginPos.Y * worldAxisY;

            canvas.PushState();
            {
                // Configure the canvas so our shapes are properly rotated and scaled
                canvas.State.TransformHandle = -localRect.TopLeft;
                canvas.State.TransformAngle = transform.Angle;
                canvas.State.TransformScale = new Vector2(transform.Scale);

                // Fill all highlighted tiles that are currently visible
                {
                    canvas.State.SetMaterial(defaultMaterial);
                    canvas.State.ColorTint = fillTint * ColorRgba.White.WithAlpha(selection ? 0.2f : 0.375f);

                    // Determine tile visibility
                    Vector2 worldTilemapOriginPos = localRect.TopLeft;
                    MathF.TransformCoord(ref worldTilemapOriginPos.X, ref worldTilemapOriginPos.Y, transform.Angle, transform.Scale);
                    TilemapCulling.TileInput cullingIn = new TilemapCulling.TileInput
                    {
                        // Remember: All these transform values are in world space
                        TilemapPos = transform.Pos + new Vector3(worldTilemapOriginPos) + new Vector3(worldOriginPos),
                        TilemapScale = transform.Scale,
                        TilemapAngle = transform.Angle,
                        TileCount = new Point2(highlight.Width, highlight.Height),
                        TileSize = tileSize
                    };
                    TilemapCulling.TileOutput cullingOut = TilemapCulling.GetVisibleTileRect(canvas.DrawDevice, cullingIn);
                    int renderedTileCount = cullingOut.VisibleTileCount.X * cullingOut.VisibleTileCount.Y;

                    // Draw all visible highlighted tiles
                    {
                        Point2 tileGridPos = cullingOut.VisibleTileStart;
                        Vector2 renderStartPos = worldOriginPos + tileGridPos.X * tileSize.X * worldAxisX + tileGridPos.Y * tileSize.Y * worldAxisY;;
                        Vector2 renderPos = renderStartPos;
                        Vector2 tileXStep = worldAxisX * tileSize.X;
                        Vector2 tileYStep = worldAxisY * tileSize.Y;
                        int lineMergeCount = 0;
                        int totalRects = 0;
                        for (int tileIndex = 0; tileIndex < renderedTileCount; tileIndex++)
                        {
                            bool current = highlight[tileGridPos.X, tileGridPos.Y];
                            if (current)
                            {
                                // Try to merge consecutive rects in the same line to reduce drawcalls / CPU load
                                bool hasNext = (tileGridPos.X + 1 < highlight.Width) && ((tileGridPos.X + 1 - cullingOut.VisibleTileStart.X) < cullingOut.VisibleTileCount.X);
                                bool next = hasNext ? highlight[tileGridPos.X + 1, tileGridPos.Y] : false;
                                if (next)
                                {
                                    lineMergeCount++;
                                }
                                else
                                {
                                    totalRects++;
                                    canvas.FillRect(
                                        transform.Pos.X + renderPos.X - lineMergeCount * tileXStep.X,
                                        transform.Pos.Y + renderPos.Y - lineMergeCount * tileXStep.Y,
                                        transform.Pos.Z,
                                        tileSize.X * (1 + lineMergeCount),
                                        tileSize.Y);
                                    lineMergeCount = 0;
                                }
                            }

                            tileGridPos.X++;
                            renderPos += tileXStep;
                            if ((tileGridPos.X - cullingOut.VisibleTileStart.X) >= cullingOut.VisibleTileCount.X)
                            {
                                tileGridPos.X = cullingOut.VisibleTileStart.X;
                                tileGridPos.Y++;
                                renderPos = renderStartPos;
                                renderPos += tileYStep * (tileGridPos.Y - cullingOut.VisibleTileStart.Y);
                            }
                        }
                    }
                }

                // Draw highlight area outlines, unless flagged as uncertain
                if (!uncertain)
                {
                    // Determine the outlines of individual highlighted tile patches
                    if (outlineCache == null) outlineCache = new List<Vector2[]>();
                    if (outlineCache.Count == 0)
                    {
                        GetTileAreaOutlines(highlight, tileSize, ref outlineCache);
                    }

                    // Draw outlines around all highlighted tile patches
                    canvas.State.SetMaterial(selection ? strippleMaterial : defaultMaterial);
                    canvas.State.ColorTint = outlineTint;
                    foreach (Vector2[] outline in outlineCache)
                    {
                        // For strippled-line display, determine total length of outline
                        if (selection)
                        {
                            float totalLength = 0.0f;
                            for (int i = 1; i < outline.Length; i++)
                            {
                                totalLength += (outline[i - 1] - outline[i]).Length;
                            }
                            canvas.State.TextureCoordinateRect = new Rect(totalLength / strippledLineTex.PixelWidth, 1.0f);
                        }

                        // Draw the outline
                        canvas.DrawPolygon(
                            outline,
                            transform.Pos.X + worldOriginPos.X,
                            transform.Pos.Y + worldOriginPos.Y,
                            transform.Pos.Z);
                    }
                }

                // If this is an uncertain highlight, i.e. not actually reflecting the represented action,
                // draw a gizmo to indicate this for the user.
                if (uncertain)
                {
                    Vector2 highlightSize = new Vector2(highlight.Width * tileSize.X, highlight.Height * tileSize.Y);
                    Vector2 highlightCenter = highlightSize * 0.5f;

                    Vector3 circlePos = transform.Pos + new Vector3(worldOriginPos + worldAxisX * highlightCenter + worldAxisY * highlightCenter);
                    float circleRadius = MathF.Min(tileSize.X, tileSize.Y) * 0.2f;

                    canvas.State.SetMaterial(defaultMaterial);
                    canvas.State.ColorTint = outlineTint;
                    canvas.FillCircle(
                        circlePos.X,
                        circlePos.Y,
                        circlePos.Z,
                        circleRadius);
                }
            }
            canvas.PopState();
        }
示例#56
0
        public void SetFormat(BitmapFormat format)
        {
            m_format = format;

            LibVlcMethods.libvlc_video_set_format(m_hMediaPlayer, m_format.Chroma.ToUtf8(), m_format.Width, m_format.Height, m_format.Pitch);
            m_pBuffer = MemoryHeap.Alloc(m_format.ImageSize);

            m_pixelData = new PixelData(m_format.ImageSize);
            m_pixelDataPtr = GCHandle.Alloc(m_pixelData, GCHandleType.Pinned);
            LibVlcMethods.libvlc_video_set_callbacks(m_hMediaPlayer, pLockCallback, pUnlockCallback, pDisplayCallback, m_pixelDataPtr.AddrOfPinnedObject());
        }
示例#57
0
 public void SetPixel(int x, int y, PixelData colour)
 {
     PixelData* pixel = PixelAt(x, y);
     *pixel = colour;
 }
示例#58
0
        //-------------------------------------------------------------------------
        /// <summary>
        /// Iterates through the pixels of the bitmap image. For each pixel, the
        /// specified <code>delegate</code> is called.  Pixels are enumerated from
        /// the top left corner of the image, line by line. The <see cref="PixelData"/>
        /// is updated at each step of the enumeration; that is, a new
        /// <see cref="PixelData"/> instance is not created at each step. Modifying
        /// the <see cref="PixelData"/> will modify the bitmap image when the
        /// <see cref="Dispose"/> or <see cref="Flush"/> is invoked on the bitmap
        /// handler.
        /// </summary>
        /// <param name="enumerator">The <code>delegate</code> that will handle
        /// pixel enumeration.</param>
        public void Enumerate(EnumerationHandler enumerator)
        {
            if (!Locked)
              {
            throw new InvalidOperationException("The bitmap is no longer locked; pixel information is no longer maintained.");
              }

              PixelData pixel = new PixelData();
              for (int ycoordinate = 0; ycoordinate < Bitmap.Height; ++ycoordinate)
              {
            int offset = ycoordinate * this.bitmapData.Stride;
            for (int xcoordinate = 0; xcoordinate < Bitmap.Width; ++xcoordinate)
            {
              int bIndex = offset + xcoordinate * BYTES_PER_PIXEL;
              int gIndex = bIndex + 1;
              int rIndex = gIndex + 1;
              pixel.X = xcoordinate;
              pixel.Y = ycoordinate;
              pixel.R = this.pixelData[rIndex];
              pixel.G = this.pixelData[gIndex];
              pixel.B = this.pixelData[bIndex];

              enumerator(pixel);

              this.pixelData[rIndex] = pixel.R;
              this.pixelData[gIndex] = pixel.G;
              this.pixelData[bIndex] = pixel.B;
            }
              }
        }
示例#59
0
        public static unsafe void drawTileWithColor(Rectangle srcArea, BitmapData srcData, Rectangle dstArea, BitmapData dstData, PixelData fgColor, PixelData bgColor)
        {
            if (srcData == null || dstData == null)
                return;

            int stride1 = srcData.Stride;
            int num1 = (int)srcData.Scan0 + srcArea.X * 4 + srcArea.Y * stride1;

            int stride2 = dstData.Stride;
            int num2 = (int)dstData.Scan0 + dstArea.X * 4 + dstArea.Y * stride2;

            int width = srcArea.Width;
            int height = srcArea.Height;

            for (int yAxis = 0; yAxis < height; ++yAxis) {
                int num3 = num1 + yAxis * stride1;
                int num4 = num2 + yAxis * stride2;

                for (int xAxis = 0; xAxis < width; ++xAxis) {
                    PixelData over = *(PixelData*)num3;

                    over.red = (byte)(((int)over.red * (int)fgColor.red + 127) / 255);
                    over.green = (byte)(((int)over.green * (int)fgColor.green + 127) / 255);
                    over.blue = (byte)(((int)over.blue * (int)fgColor.blue + 127) / 255);

                    *(PixelData*)num4 = PixelData.overlayPixelData(over, bgColor);
                    num3 += 4;
                    num4 += 4;
                }
            }
        }
示例#60
0
        public static float[] GetUnscaledPixels(PixelData data, ImageProperties properties)
        {
            //Set up matrix
            int frames = properties.NumberOfFrames > 0 ? properties.NumberOfFrames : 1;
            float[] values = new float[properties.Rows * properties.Columns * frames];

            //Check encapsulation
            if (data.Format == FrameDataFormat.NATIVE)
            {
                using (BinaryReader r = new BinaryReader(new MemoryStream(data.ByteData)))
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = GetNativePixelsUnscaled(r, properties);
                    }
                }
            }
            else
            {
                //This is not implemented yet
                CompressionHelper.Decompress(data, properties, ref values);
            }

            return values;
        }