コード例 #1
0
ファイル: ImageProtocol.cs プロジェクト: xamarin/mac-samples
		static NSImage Render (string value)
		{
			NSImage image = null;

			NSApplication.SharedApplication.InvokeOnMainThread (() =>
			{
				NSString text = new NSString (string.IsNullOrEmpty (value) ? " " : value);
				NSFont font = NSFont.FromFontName ("Arial", 20);
				var fontDictionary = NSDictionary.FromObjectsAndKeys (new NSObject[] { font, NSColor.Red }, new NSObject[] { NSStringAttributeKey.Font, NSStringAttributeKey.ForegroundColor });
				CGSize size = text.StringSize (fontDictionary);

				image = new NSImage (new CGSize (size));

				image.LockFocus ();
				text.DrawString (new CGPoint (0, 0), fontDictionary);
				image.UnlockFocus ();
			});

			return image;
		}
コード例 #2
0
        private NSImage GetImage()
        {
            using (var src = NSImage.FromStream(System.IO.File.OpenRead(filePath)))
            {
                var imageSize = src.Size;
                var thumbnailSize = new CGSize(Math.Ceiling(BarHeight * imageSize.Width / imageSize.Height), BarHeight);

                var thumbnail = new NSImage(thumbnailSize);
                thumbnail.LockFocus();
                src.Draw(new CGRect(CGPoint.Empty, thumbnailSize), new CGRect(CGPoint.Empty, imageSize), NSCompositingOperation.SourceOver, 1f);
                thumbnail.UnlockFocus();
                return thumbnail;
            }
        }
コード例 #3
0
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight = -1,
            int inputWidth  = -1,
            float inputMean = 0.0f,
            float scale     = 1.0f)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#else
            if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows)
            {
                //Do something for Windows
                System.Drawing.Bitmap bmp = new Bitmap(fileName);

                if (inputHeight > 0 || inputWidth > 0)
                {
                    //resize bmp
                    System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight);
                    bmp.Dispose();
                    bmp = newBmp;
                    //bmp.Save("tmp.png");
                }

                byte[] byteValues = new byte[bmp.Width * bmp.Height * 3];
                System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();

                bmp.LockBits(
                    new Rectangle(0, 0, bmp.Width, bmp.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd);
                Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length);
                bmp.UnlockBits(bd);

                if (typeof(T) == typeof(float))
                {
                    float[] floatValues = new float[bmp.Width * bmp.Height * 3];
                    for (int i = 0; i < byteValues.Length; ++i)
                    {
                        floatValues[i] = ((float)byteValues[i] - inputMean) * scale;
                    }
                    Marshal.Copy(floatValues, 0, dest, floatValues.Length);
                }
                else if (typeof(T) == typeof(byte))
                {
                    bool swapBR = false;
                    if (swapBR)
                    {
                        int    imageSize = bmp.Width * bmp.Height;
                        byte[] bValues   = new byte[imageSize * 3];
                        for (int i = 0; i < imageSize; ++i)
                        {
                            bValues[i * 3]     = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale);
                            bValues[i * 3 + 1] = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale);
                            bValues[i * 3 + 2] = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale);
                        }
                        Marshal.Copy(bValues, 0, dest, bValues.Length);
                    }
                    else
                    {
                        if (!(inputMean == 0.0f && scale == 1.0f))
                        {
                            for (int i = 0; i < byteValues.Length; ++i)
                            {
                                byteValues[i] = (byte)(((float)byteValues[i] - inputMean) * scale);
                            }
                        }
                        Marshal.Copy(byteValues, 0, dest, byteValues.Length);
                    }
                }
                else
                {
                    throw new Exception(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
                }
            }
            else
            {
                throw new Exception("Not implemented");
            }
#endif
        }
コード例 #4
0
ファイル: BitmapFont.cs プロジェクト: RangoLee/mac-samples
		// Create the set of display lists for the bitmaps
		bool MakeGLDisplayListFirst (char first, int count, int baseDL)
		{

			int curListIndex;
			NSColor blackColor;
			NSStringAttributes attribDict;
			int dListNum;
			NSString currentChar;
			char currentUnichar;
			CGSize charSize;
			CGRect charRect = CGRect.Empty;
			NSImage theImage;
			bool retval;

			// Make sure the list isn't already under construction
			GL.GetInteger (GetPName.ListIndex, out curListIndex);
			if (curListIndex != 0) {
				Console.WriteLine ("Display list already under construction");
				return false;
			}

			// Save pixel unpacking state
			GL.PushClientAttrib (ClientAttribMask.ClientPixelStoreBit);

			GL.PixelStore (PixelStoreParameter.UnpackSwapBytes, 0);
			GL.PixelStore (PixelStoreParameter.UnpackLsbFirst, 0);
			GL.PixelStore (PixelStoreParameter.UnpackSkipPixels, 0);
			GL.PixelStore (PixelStoreParameter.UnpackSkipRows, 0);
			GL.PixelStore (PixelStoreParameter.UnpackRowLength, 0);
			GL.PixelStore (PixelStoreParameter.UnpackAlignment, 0);

			blackColor = NSColor.Black;

			attribDict = new NSStringAttributes {
				Font = font,
				ForegroundColor = NSColor.White,
				BackgroundColor = blackColor
			};

			theImage = new NSImage (new CGSize (0,0));
			retval = true;

			for (dListNum = baseDL, currentUnichar = first; currentUnichar < first + count; 
				dListNum++, currentUnichar++) {

				currentChar = new NSString (Char.ToString (currentUnichar));
				charSize = currentChar.StringSize (attribDict);
				charRect.Size = charSize;
				charRect = charRect.Integral ();
				if (charRect.Size.Width > 0 && charRect.Size.Height > 0) {

					theImage.Size = charRect.Size;
					theImage.LockFocus ();
					NSGraphicsContext.CurrentContext.ShouldAntialias = false;
					blackColor.Set ();
					NSBezierPath.FillRect (charRect);
					currentChar.DrawString (charRect, attribDict.Dictionary);
					theImage.UnlockFocus ();

					if (!MakeDisplayList(dListNum, theImage)) {
						retval = false;
						break;
					}
				}
			}
			return retval;
		}
コード例 #5
0
        // Create the set of display lists for the bitmaps
        bool MakeGLDisplayListFirst(char first, int count, int baseDL)
        {
            int                 curListIndex;
            NSColor             blackColor;
            NSMutableDictionary attribDict;
            int                 dListNum;
            NSString            currentChar;
            char                currentUnichar;
            CGSize              charSize;
            CGRect              charRect = CGRect.Empty;
            NSImage             theImage;
            bool                retval;

            // Make sure the list isn't already under construction
            GL.GetInteger(GetPName.ListIndex, out curListIndex);
            if (curListIndex != 0)
            {
                Console.WriteLine("Display list already under construction");
                return(false);
            }

            // Save pixel unpacking state
            GL.PushClientAttrib(ClientAttribMask.ClientPixelStoreBit);

            GL.PixelStore(PixelStoreParameter.UnpackSwapBytes, 0);
            GL.PixelStore(PixelStoreParameter.UnpackLsbFirst, 0);
            GL.PixelStore(PixelStoreParameter.UnpackSkipPixels, 0);
            GL.PixelStore(PixelStoreParameter.UnpackSkipRows, 0);
            GL.PixelStore(PixelStoreParameter.UnpackRowLength, 0);
            GL.PixelStore(PixelStoreParameter.UnpackAlignment, 0);

            blackColor = NSColor.Black;

            attribDict = new NSMutableDictionary();
            attribDict.SetValueForKey(font, NSAttributedString.FontAttributeName);
            attribDict.SetValueForKey(NSColor.White, NSAttributedString.ForegroundColorAttributeName);
            attribDict.SetValueForKey(blackColor, NSAttributedString.BackgroundColorAttributeName);

            theImage = new NSImage(new CGSize(0, 0));
            retval   = true;

            for (dListNum = baseDL, currentUnichar = first; currentUnichar < first + count;
                 dListNum++, currentUnichar++)
            {
                currentChar   = new NSString(Char.ToString(currentUnichar));
                charSize      = currentChar.StringSize(attribDict);
                charRect.Size = charSize;
                charRect      = charRect.Integral();
                if (charRect.Size.Width > 0 && charRect.Size.Height > 0)
                {
                    theImage.Size = charRect.Size;
                    theImage.LockFocus();
                    NSGraphicsContext.CurrentContext.ShouldAntialias = false;
                    blackColor.Set();
                    NSBezierPath.FillRect(charRect);
                    currentChar.DrawString(charRect, attribDict);
                    theImage.UnlockFocus();

                    if (!MakeDisplayList(dListNum, theImage))
                    {
                        retval = false;
                        break;
                    }
                }
            }
            return(retval);
        }
コード例 #6
0
        public static SCNNode SCBoxNode(string title, CGRect frame, NSColor color, float cornerRadius, bool centered)
        {
            NSStringAttributes titleAttributes         = null;
            NSStringAttributes centeredTitleAttributes = null;

            // create and extrude a bezier path to build the box
            var path = NSBezierPath.FromRoundedRect(frame, cornerRadius, cornerRadius);

            path.Flatness = 0.05f;

            var shape = SCNShape.Create(path, 20);

            shape.ChamferRadius = 0.0f;

            var node = SCNNode.Create();

            node.Geometry = shape;

            // create an image and fill with the color and text
            var textureSize = new CGSize();

            textureSize.Width  = NMath.Ceiling(frame.Size.Width * 1.5f);
            textureSize.Height = NMath.Ceiling(frame.Size.Height * 1.5f);

            var texture = new NSImage(textureSize);

            texture.LockFocus();

            var drawFrame = new CGRect(0, 0, textureSize.Width, textureSize.Height);

            nfloat hue, saturation, brightness, alpha;

            (color.UsingColorSpace(NSColorSpace.DeviceRGBColorSpace)).GetHsba(out hue, out saturation, out brightness, out alpha);
            var lightColor = NSColor.FromDeviceHsba(hue, saturation - 0.2f, brightness + 0.3f, alpha);

            lightColor.Set();

            NSGraphics.RectFill(drawFrame);

            NSBezierPath fillpath = null;

            if (cornerRadius == 0 && centered == false)
            {
                //special case for the "labs" slide
                drawFrame.Offset(0, -2);
                fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius);
            }
            else
            {
                drawFrame.Inflate(-3, -3);
                fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius);
            }

            color.Set();
            fillpath.Fill();

            // draw the title if any
            if (title != null)
            {
                if (titleAttributes == null)
                {
                    var paraphStyle = new NSMutableParagraphStyle();
                    paraphStyle.LineBreakMode     = NSLineBreakMode.ByWordWrapping;
                    paraphStyle.Alignment         = NSTextAlignment.Center;
                    paraphStyle.MinimumLineHeight = 38;
                    paraphStyle.MaximumLineHeight = 38;

                    var font = NSFont.FromFontName("Myriad Set Semibold", 34) != null?NSFont.FromFontName("Myriad Set Semibold", 34) : NSFont.FromFontName("Avenir Medium", 34);

                    var shadow = new NSShadow();
                    shadow.ShadowOffset     = new CGSize(0, -2);
                    shadow.ShadowBlurRadius = 4;
                    shadow.ShadowColor      = NSColor.FromDeviceWhite(0.0f, 0.5f);

                    titleAttributes = new NSStringAttributes {
                        Font            = font,
                        ForegroundColor = NSColor.White,
                        Shadow          = shadow,
                        ParagraphStyle  = paraphStyle
                    };

                    var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy();
                    centeredParaphStyle.Alignment = NSTextAlignment.Center;

                    centeredTitleAttributes = new NSStringAttributes {
                        Font            = font,
                        ForegroundColor = NSColor.White,
                        Shadow          = shadow,
                        ParagraphStyle  = paraphStyle
                    };
                }

                var attrString = new NSAttributedString(title, centered ? centeredTitleAttributes : titleAttributes);
                var textSize   = attrString.Size;

                //check if we need two lines to draw the text
                var twoLines = title.Contains("\n");
                if (!twoLines)
                {
                    twoLines = textSize.Width > frame.Size.Width && title.Contains(" ");
                }

                //if so, we need to adjust the size to center vertically
                if (twoLines)
                {
                    textSize.Height += 38;
                }

                if (!centered)
                {
                    drawFrame.Inflate(-15, 0);
                }

                //center vertically
                var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f;
                var drawFrameHeight = drawFrame.Size.Height;
                drawFrame.Size = new CGSize(drawFrame.Size.Width, drawFrame.Size.Height - dy);
                attrString.DrawString(drawFrame);
            }

            texture.UnlockFocus();

            //set the created image as the diffuse texture of our 3D box
            var front = SCNMaterial.Create();

            front.Diffuse.Contents        = texture;
            front.LocksAmbientWithDiffuse = true;

            //use a lighter color for the chamfer and sides
            var sides = SCNMaterial.Create();

            sides.Diffuse.Contents  = lightColor;
            node.Geometry.Materials = new SCNMaterial[] {
                front,
                sides,
                sides,
                sides,
                sides
            };

            return(node);
        }
コード例 #7
0
ファイル: YACRSUtil.cs プロジェクト: niallb/YACRSMac
        public static byte[] grabScreenAsPNG(CGPoint containing)
        {
            // Grab screen
            // Mac stuff from http://stackoverflow.com/questions/18851247/screen-capture-on-osx-using-monomac
            NSScreen screen = NSScreen.MainScreen;

            if ((containing.X >= 0) && (containing.Y >= 0))
            {
                int  idx   = 0;
                bool found = false;
                while (!found && (idx < NSScreen.Screens.Length))
                {
                    if (NSScreen.Screens[idx].Frame.Contains(containing))
                    {
                        found  = true;
                        screen = NSScreen.Screens[idx];
                    }
                    idx++;
                }
            }

            //System.Drawing.RectangleF bounds = new RectangleF(0,0,screen.Frame.GetMaxX(),screen.Frame.GetMaxY());
            CGRect bounds = new CGRect((float)screen.Frame.GetMinX(), (float)screen.Frame.GetMinY(), (float)screen.Frame.GetMaxX(), (float)screen.Frame.GetMaxY());

            //System.Drawing.Image si2;
            //NSImage si2;

            //  CGImage screenImage = MonoMac.CoreGraphics.CGImage.ScreenImage(0,bounds);
            screenImage = ScreenImage2(0, bounds, CGWindowListOption.All, CGWindowImageOption.Default);


            #pragma warning disable XS0001 // Find usages of mono todo items

            /*using(NSBitmapImageRep imageRep = new NSBitmapImageRep(screenImage))
             * {
             *  NSDictionary properties = NSDictionary.FromObjectAndKey(new NSNumber(1.0), new NSString("NSImageCompressionFactor"));
             *  using(NSData tiffData = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, properties))
             *  {
             *
             *      using (var ms = new MemoryStream())
             *
             *      {
             *          tiffData.AsStream().CopyTo(ms);
             *          si2 = NSImage.FromStream(ms);
             *          //si2 = System.Drawing.Image.FromStream (ms, true);
             *      }
             *  }
             * }*/
            NSBitmapImageRep si2 = new NSBitmapImageRep(screenImage);



            int     newHeight = (int)((si2.Size.Height * imgWidth) / si2.Size.Width);
            CGSize  destSize  = new CGSize(imgWidth, newHeight);
            NSImage resized2  = new NSImage(destSize);
            resized2.LockFocus();
            CGRect sz = new CGRect(0, 0, imgWidth, newHeight);
            //si2.DrawInRect(sz, new CGRect(0, 0, si2.Size.Width, si2.Size.Height), NSCompositingOperation.SourceOver, 1);
            si2.DrawInRect(sz);
            resized2.UnlockFocus();
            resized2.Size = destSize;

            //Bitmap resized = new Bitmap(imgWidth, newHeight, PixelFormat.Format24bppRgb);
            //Graphics g = Graphics.FromImage (resized);
            //g.DrawImage (si2, 0, 0, imgWidth, newHeight);

            NSBitmapImageRep newRep  = new NSBitmapImageRep(resized2.AsCGImage(ref sz, null, null));
            NSData           pngData = newRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);

            screenImage.Dispose();

            byte[] result = null;

            result = pngData.ToArray();
            //using (MemoryStream stream = new MemoryStream())
            //{
            //
            //
            //	resized.Save(stream, ImageFormat.Png);
            //    result = stream.ToArray();
            //}
            return(result);
        }
コード例 #8
0
		NSImage MakeRotatedCopy (NSImage original, float degrees)
		{
			var copy = new NSImage (original.Size);
			copy.LockFocus ();
			try {
				var rot = new NSAffineTransform ();
				rot.Translate (original.Size.Width / 2, original.Size.Height / 2);
				rot.RotateByDegrees (degrees);
				rot.Translate (-original.Size.Width / 2, -original.Size.Height / 2);
				rot.Concat ();
				original.Draw (CGPoint.Empty, CGRect.Empty, NSCompositingOperation.Copy, 1);
			} finally {
				copy.UnlockFocus ();
			}
			return copy;
		}
コード例 #9
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= (int)contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            // font
            NSFont font = null;

            var ext = System.IO.Path.GetExtension(textDef.FontName);

            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                try
                {
                    textDef.FontName = LoadFontFile(textDef.FontName);
                    font             = NSFont.FromFontName(textDef.FontName, textDef.FontSize);
                }
                catch (Exception exc)
                {
                    CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName);
                }
            }
            else
            {
                // font
                font = NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize);
            }

            if (font == null)
            {
                font = NSFontManager.SharedFontManager.FontWithFamily("Arial", NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize);
                CCLog.Log("{0} not found.  Defaulting to Arial.", textDef.FontName);
            }

            // color
            var fontColor       = textDef.FontFillColor;
            var fontAlpha       = textDef.FontAlpha;
            var foregroundColor = NSColor.FromDeviceRgba(fontColor.R / 255.0f,
                                                         fontColor.G / 255.0f,
                                                         fontColor.B / 255.0f,
                                                         fontAlpha / 255.0f);

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? NSTextAlignment.Right
                : (CCTextAlignment.Center == horizontalAlignment) ? NSTextAlignment.Center
                : NSTextAlignment.Left;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? NSLineBreakMode.CharWrapping
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? NSLineBreakMode.ByWordWrapping
                : NSLineBreakMode.Clipping;

            var nsparagraphStyle = new NSMutableParagraphStyle();

            nsparagraphStyle.SetParagraphStyle(NSMutableParagraphStyle.DefaultParagraphStyle);
            nsparagraphStyle.LineBreakMode = lineBreak;
            nsparagraphStyle.Alignment     = textAlign;

            // Create a new attributed string definition
            var nsAttributes = new NSStringAttributes();

            // Font attribute
            nsAttributes.Font            = font;
            nsAttributes.ForegroundColor = foregroundColor;
            nsAttributes.ParagraphStyle  = nsparagraphStyle;

            var stringWithAttributes = new NSAttributedString(text, nsAttributes);

            var realDimensions = stringWithAttributes.Size;

            // Mac crashes if the width or height is 0
            if (realDimensions == SizeF.Empty)
            {
                CCLog.Log("Native string:", "Dimensions of native NSAttributedString can not be 0,0");
                return(new CCTexture2D());
            }

            var dimensions = new SizeF(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            //
            // * Note * This seems to only effect Mac because iOS works fine without this work around.
            // Right Alignment BoundingRectWithSize does not seem to be working correctly when the following conditions are set:
            //      1) Alignment Right
            //      2) No dimensions
            //      3) There are new line characters embedded in the string.
            //
            // So we set alignment to Left, calculate our bounds and then restore alignement afterwards before drawing.
            //
            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;

                // Set our alignment variables to left - see notes above.
                nsparagraphStyle.Alignment = NSTextAlignment.Left;
                stringWithAttributes.Dispose();
                stringWithAttributes = null;
                stringWithAttributes = new NSAttributedString(text, nsAttributes);
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }

            // Calculate our bounding rectangle
            var boundingRect = stringWithAttributes.BoundingRectWithSize(new SizeF((int)dimensions.Width, (int)dimensions.Height),
                                                                         NSStringDrawingOptions.UsesLineFragmentOrigin);

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;

                    // Restore our alignment before drawing - see notes above.
                    nsparagraphStyle.Alignment = textAlign;
                    stringWithAttributes.Dispose();
                    stringWithAttributes = null;
                    stringWithAttributes = new NSAttributedString(text, nsAttributes);
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Alignment
            var xOffset = 0.0f;

            switch (textAlign)
            {
            case NSTextAlignment.Left:
                xOffset = 0;
                break;

            case NSTextAlignment.Center:
                xOffset = (dimensions.Width - boundingRect.Width) / 2.0f;
                break;

            case NSTextAlignment.Right: xOffset = dimensions.Width - boundingRect.Width; break;

            default: break;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Top == verticleAlignement ||
                           boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to top
                : (CCVerticalTextAlignment.Bottom == verticleAlignement) ? 0                                     // align to bottom
                : (imageHeight - boundingRect.Height) / 2.0f;                                                    // align to center

            //Find the rect that the string will draw into inside the dimensions
            var drawRect = new RectangleF(xOffset
                                          , yOffset
                                          , boundingRect.Width
                                          , boundingRect.Height);


            NSImage image = null;

            try
            {
                //Set antialias or not
                NSGraphicsContext.CurrentContext.ShouldAntialias = textDef.isShouldAntialias;

                image = new NSImage(new SizeF(imageWidth, imageHeight));

                image.LockFocus();

                // set a default transform
                var transform = new NSAffineTransform();
                transform.Set();

                stringWithAttributes.DrawInRect(drawRect);

                image.UnlockFocus();

                // We will use Texture2D from stream here instead of CCTexture2D stream.
                var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, image);

                // Debugging purposes
//            var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//            var fileName = Path.Combine(path, "Label3.png");
//            using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
//            {
//                tex.SaveAsPng(stream, imageWidth, imageHeight);
//            }

                // Create our texture of the label string.
                var texture = new CCTexture2D(tex);

                return(texture);
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace);
            }
            finally
            {
                // clean up the resources
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }
                if (stringWithAttributes != null)
                {
                    stringWithAttributes.Dispose();
                    stringWithAttributes = null;
                }
            }
            return(new CCTexture2D());
        }
コード例 #10
0
        public override void UpdateLayer()
        {
            base.UpdateLayer();

            if (image != null && imageLayer == null)
            {
                Layer.MasksToBounds = false;

                if (maskLayer == null)
                {
                    maskLayer = CAShapeLayer.Create() as CAShapeLayer;
                    Layer.AddSublayer(maskLayer);
                    maskLayer.Path = CGPath.FromRoundedRect(Bounds, cornerRadius, cornerRadius);
                }

                imageLayer               = CALayer.Create();
                imageLayer.Mask          = maskLayer;
                imageLayer.MasksToBounds = true;

                image.LockFocus();
                imageLayer.Contents        = image.CGImage;
                imageLayer.ContentsGravity = CALayer.GravityResizeAspectFill;
                image.UnlockFocus();

                Layer.AddSublayer(imageLayer);
            }

            if (image == null)
            {
                imageLayer?.RemoveFromSuperLayer();
            }

            if (overlayAlpha > 0 && overlayLayer == null)
            {
                overlayLayer = new CALayer();
                overlayLayer.BackgroundColor = overlayColor.ColorWithAlphaComponent(overlayAlpha).CGColor;
                Layer.AddSublayer(overlayLayer);
            }

            if (overlayAlpha == 0 && overlayLayer != null)
            {
                overlayLayer.RemoveFromSuperLayer();
                overlayLayer = null;
            }

            CATransaction.Begin();
            CATransaction.DisableActions = true;

            if (imageLayer != null)
            {
                if (imageLayer.Bounds.Width != Bounds.Width)
                {
                    imageLayer.Frame = Bounds;
                    maskLayer.Path   = CGPath.FromRoundedRect(Bounds, cornerRadius, cornerRadius);
                }
            }

            if (overlayLayer != null && overlayLayer.SuperLayer != null && overlayLayer.Frame != Bounds)
            {
                overlayLayer.Frame = Bounds;
            }

            CATransaction.Commit();
        }
コード例 #11
0
        public static XIR.Image RemoteRepresentation(this NSLineCapStyle obj)
        {
            // Customize the line cap style for the new object.
            var aPath       = new NSBezierPath();
            var lineWidth   = 16;
            var sampleWidth = 100;

            // First we draw the presentation line
            aPath.LineWidth = lineWidth;
            aPath.MoveTo(new CGPoint(lineWidth, lineWidth));
            aPath.LineTo(new CGPoint(lineWidth + sampleWidth, lineWidth));

            switch ((NSLineCapStyle)obj)
            {
            case NSLineCapStyle.Square:
                aPath.LineCapStyle = NSLineCapStyle.Square;
                break;

            case NSLineCapStyle.Butt:
                aPath.LineCapStyle = NSLineCapStyle.Butt;
                break;

            case NSLineCapStyle.Round:
                aPath.LineCapStyle = NSLineCapStyle.Round;
                break;
            }

            // let's make sure we leave a little room for the line width drawing as well by adding the lineWidth as well
            var width  = aPath.ControlPointBounds.Right + lineWidth;
            var height = aPath.ControlPointBounds.Bottom + lineWidth;

            var nsimage = new NSImage(new CGSize(width, height));

            nsimage.LockFocus();

            // We need to offset the image a little so it will not be cut off
            var transform = new NSAffineTransform();

            transform.Translate(aPath.LineWidth / 2, aPath.LineWidth / 2);
            aPath.TransformUsingAffineTransform(transform);

            brush.Set();
            aPath.Stroke();

            // Second, we draw the inset line to demonstrate the bounds
            aPath.RemoveAllPoints();
            lineWidth      += lineWidth / 2;
            aPath.LineWidth = 2;
            aPath.MoveTo(new CGPoint(lineWidth, lineWidth));
            aPath.LineTo(new CGPoint(lineWidth + sampleWidth, lineWidth));

            pen.Set();
            aPath.Stroke();

            // Third, we draw the inset line endings which are two circles
            aPath.RemoveAllPoints();
            var circleWidth = 2;

            aPath.LineWidth    = circleWidth;
            aPath.LineCapStyle = NSLineCapStyle.Butt;
            aPath.AppendPathWithOvalInRect(new CGRect(lineWidth - (int)(circleWidth / 2), lineWidth - (int)(circleWidth / 2), circleWidth, circleWidth));
            aPath.AppendPathWithOvalInRect(new CGRect(lineWidth + sampleWidth - (int)(circleWidth / 2), lineWidth - (int)(circleWidth / 2), circleWidth, circleWidth));

            pen.Set();
            aPath.Stroke();
            nsimage.UnlockFocus();
            return(nsimage.RemoteRepresentation());
        }
コード例 #12
0
        public static void ReadImageFileToTensor(String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f)
        {
#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);

            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }
            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);
            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }

            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __IOS__
            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            for (int i = 0; i < intValues.Length; ++i)
            {
                int val = intValues[i];
                floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
            }
            System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#else
            throw new Exception("Not implemented");
#endif
        }
コード例 #13
0
        /// <summary>
        /// Read a NSImage, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="image">The input image</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        public static void ReadImageToTensor <T>(
            NSImage image,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            NSImage resized;

            if (inputHeight > 0 || inputWidth > 0)
            {
                resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
            }
            else
            {
                resized = image;
            }

            int[]   intValues   = new int[(int)(resized.Size.Width * resized.Size.Height)];
            float[] floatValues = new float[(int)(resized.Size.Width * resized.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = resized.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)resized.Size.Width,
                               (nint)resized.Size.Height,
                               8,
                               (nint)resized.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), resized.Size), cgimage);
                    }
            handle.Free();
            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
            if (resized != image)
            {
                resized.Dispose();
            }
        }
コード例 #14
0
        /// <summary>
        /// Read an image file, covert the data and save it to the native pointer
        /// </summary>
        /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam>
        /// <param name="fileName">The name of the image file</param>
        /// <param name="dest">The native pointer where the image pixels values will be saved to.</param>
        /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param>
        /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param>
        /// <param name="inputMean">The mean value, it will be substracted from the input image pixel values</param>
        /// <param name="scale">The scale, after mean is substracted, the scale will be used to multiply the pixel values</param>
        /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param>
        /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param>
        public static void ReadImageFileToTensor <T>(
            String fileName,
            IntPtr dest,
            int inputHeight     = -1,
            int inputWidth      = -1,
            float inputMean     = 0.0f,
            float scale         = 1.0f,
            bool flipUpSideDown = false,
            bool swapBR         = false)
            where T : struct
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName));
            }

#if __ANDROID__
            Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false);
                bmp.Dispose();
                bmp = resized;
            }

            if (flipUpSideDown)
            {
                Matrix matrix = new Matrix();
                matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2);
                Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true);
                bmp.Dispose();
                bmp = flipped;
            }

            int[]   intValues   = new int[bmp.Width * bmp.Height];
            float[] floatValues = new float[bmp.Width * bmp.Height * 3];
            bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height);

            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }
#elif __IOS__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }

            UIImage image = new UIImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight));
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();

            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }

            //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif __UNIFIED__
            if (flipUpSideDown)
            {
                throw new NotImplementedException("Flip Up Side Down is Not implemented");
            }
            //if (swapBR)
            //    throw new NotImplementedException("swapBR is Not implemented");
            NSImage image = new NSImage(fileName);
            if (inputHeight > 0 || inputWidth > 0)
            {
                NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight));
                resized.LockFocus();
                image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f);
                resized.UnlockFocus();
                image.Dispose();
                image = resized;
            }
            int[]   intValues   = new int[(int)(image.Size.Width * image.Size.Height)];
            float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)];
            System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned);
            using (CGImage cgimage = image.CGImage)
                using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                    using (CGBitmapContext context = new CGBitmapContext(
                               handle.AddrOfPinnedObject(),
                               (nint)image.Size.Width,
                               (nint)image.Size.Height,
                               8,
                               (nint)image.Size.Width * 4,
                               cspace,
                               CGImageAlphaInfo.PremultipliedLast
                               ))
                    {
                        context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage);
                    }
            handle.Free();
            if (swapBR)
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale;
                }
            }
            else
            {
                for (int i = 0; i < intValues.Length; ++i)
                {
                    int val = intValues[i];
                    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale;
                    floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale;
                }
            }

            if (typeof(T) == typeof(float))
            {
                Marshal.Copy(floatValues, 0, dest, floatValues.Length);
            }
            else if (typeof(T) == typeof(byte))
            {
                //copy float to bytes
                byte[] byteValues = new byte[floatValues.Length];
                for (int i = 0; i < floatValues.Length; i++)
                {
                    byteValues[i] = (byte)floatValues[i];
                }
                Marshal.Copy(byteValues, 0, dest, byteValues.Length);
            }
            else
            {
                throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
            }

            //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length);
#elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE
            Texture2D texture = ReadTexture2DFromFile(fileName);
            ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false);
#else
            //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
            {
                //Read the file using Bitmap class
                System.Drawing.Bitmap bmp = new Bitmap(fileName);

                if (inputHeight > 0 || inputWidth > 0)
                {
                    //resize bmp
                    System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight);
                    bmp.Dispose();
                    bmp = newBmp;
                    //bmp.Save("tmp.png");
                }

                if (flipUpSideDown)
                {
                    bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
                }

                int bmpWidth  = bmp.Width;
                int bmpHeight = bmp.Height;
                System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();
                bmp.LockBits(
                    new Rectangle(0, 0, bmpWidth, bmpHeight),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd);
                int stride = bd.Stride;

                byte[] byteValues = new byte[bmpHeight * stride];
                Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length);
                bmp.UnlockBits(bd);

                if (typeof(T) == typeof(float))
                {
                    int     imageSize   = bmpWidth * bmpHeight;
                    float[] floatValues = new float[imageSize * 3];
                    if (swapBR)
                    {
                        int idx       = 0;
                        int rowOffset = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int rowPtr = rowOffset;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                float b = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                float g = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                float r = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = r;
                                floatValues[idx++] = g;
                                floatValues[idx++] = b;
                            }
                            rowOffset += stride;
                        }
                    }
                    else
                    {
                        int idx       = 0;
                        int rowOffset = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int rowPtr = rowOffset;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                                floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale;
                            }
                            rowOffset += stride;
                        }
                    }
                    Marshal.Copy(floatValues, 0, dest, floatValues.Length);
                }
                else if (typeof(T) == typeof(byte))
                {
                    int imageSize = bmp.Width * bmp.Height;
                    if (swapBR)
                    {
                        int idx = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int offset = i * stride;
                            for (int j = 0; j < bmpWidth; ++j)
                            {
                                byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                                byteValues[idx++] = r;
                                byteValues[idx++] = g;
                                byteValues[idx++] = b;
                            }
                        }
                    }
                    else
                    {
                        int idx = 0;
                        for (int i = 0; i < bmpHeight; ++i)
                        {
                            int offset = i * stride;
                            for (int j = 0; j < bmpWidth * 3; ++j)
                            {
                                byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale);
                            }
                        }
                    }
                    Marshal.Copy(byteValues, 0, dest, imageSize * 3);
                }
                else
                {
                    throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString()));
                }
            }

            /*
             * else //Unix
             * {
             *  //if (flipUpSideDown)
             *  //    throw new NotImplementedException("Flip Up Side Down is Not implemented");
             *
             *  throw new NotImplementedException("Not implemented");
             * }*/
#endif
        }
コード例 #15
0
ファイル: BigLetterView.cs プロジェクト: yingfangdu/BNR
        public override void MouseDragged(NSEvent theEvent)
        {
            base.MouseDragged(theEvent);
            CGPoint down = mMouseDownEvent.LocationInWindow;
            CGPoint drag = theEvent.LocationInWindow;
            // Calculate the distance between this dragging position and the mouse down position
            double distance = Math.Sqrt( Math.Pow( down.X - drag.X ,2) + Math.Pow(down.Y - drag.Y, 2) );
            // Don't do too often
            if (distance < 3) {
                return;
            }

            // And not if there is no string to drag
            if (mLetter.Length == 0) {
                return;
            }

            // Get the size of the string
            CGSize size = mLetter.StringSize(mTextAttributes);

            // Create the image that will be dragged
            NSImage anImage = new NSImage(size);

            // Create a rect in which you will draw the letter
            // in the image
            CGRect imageBounds = CGRect.Empty;
            imageBounds.Location = new CGPoint(0.0f, 0.0f);
            imageBounds.Size = size;

            // Draw the letter on the image
            anImage.LockFocus();
            DrawStringCenteredInRectangle(mLetter, imageBounds);
            anImage.UnlockFocus();

            // Get the location of the mouse down event
            CGPoint p = this.ConvertPointFromView(down, null);

            // Drag from the center of theimage
            p = new CGPoint(p.X - size.Width/2, p.Y - size.Height/2);

            // Get the pasteboard
            NSPasteboard pb = NSPasteboard.FromName(NSPasteboard.NSDragPasteboardName);

            // Put the string and the pdf image in the pasteboard
            WriteToPasteBoard(pb);

            // Start the drag - deprecated, should use BeginDraggingSession, but need to wait for new Xam.Mac. Bug filed. #26941
            this.DragImage(anImage, p,CGSize.Empty, mMouseDownEvent, pb, this, true);
        }
コード例 #16
0
		//- (NSImage *)thumbImageFromImage:(NSImage *)image;
		async Task<NSImage> ThumbImageFromImageAsync(NSImage image)
		{
			nfloat targetHeight = 200.0f;
			CGSize imageSize = image.Size;
			CGSize smallerSize = new CGSize(targetHeight * imageSize.Width / imageSize.Height, targetHeight);

			NSImage smallerImage = new NSImage(smallerSize);

			smallerImage.LockFocus();
			image.DrawInRect(new CGRect(0,0,smallerSize.Width, smallerSize.Height), CGRect.Empty, NSCompositingOperation.Copy, 1.0f);
			smallerImage.UnlockFocus();

			return smallerImage;
		}
コード例 #17
0
ファイル: Utils.cs プロジェクト: shriharipathak/mac-samples
		public static SCNNode SCBoxNode (string title, CGRect frame, NSColor color, float cornerRadius, bool centered)
		{
			NSMutableDictionary titleAttributes = null;
			NSMutableDictionary centeredTitleAttributes = null;

			// create and extrude a bezier path to build the box
			var path = NSBezierPath.FromRoundedRect (frame, cornerRadius, cornerRadius);
			path.Flatness = 0.05f;

			var shape = SCNShape.Create (path, 20);
			shape.ChamferRadius = 0.0f;

			var node = SCNNode.Create ();
			node.Geometry = shape;

			// create an image and fill with the color and text
			var textureSize = new CGSize ();
			textureSize.Width = NMath.Ceiling (frame.Size.Width * 1.5f);
			textureSize.Height = NMath.Ceiling (frame.Size.Height * 1.5f);

			var texture = new NSImage (textureSize);
			texture.LockFocus ();

			var drawFrame = new CGRect (0, 0, textureSize.Width, textureSize.Height);

			nfloat hue, saturation, brightness, alpha;

			(color.UsingColorSpace (NSColorSpace.DeviceRGBColorSpace)).GetHsba (out hue, out saturation, out brightness, out alpha);
			var lightColor = NSColor.FromDeviceHsba (hue, saturation - 0.2f, brightness + 0.3f, alpha);
			lightColor.Set ();

			NSGraphics.RectFill (drawFrame);

			NSBezierPath fillpath = null;

			if (cornerRadius == 0 && centered == false) {
				//special case for the "labs" slide
				drawFrame.Offset (0, -2);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			} else {
				drawFrame.Inflate (-3, -3);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			}

			color.Set ();
			fillpath.Fill ();

			// draw the title if any
			if (title != null) {
				if (titleAttributes == null) {
					var paraphStyle = new NSMutableParagraphStyle ();
					paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping;
					paraphStyle.Alignment = NSTextAlignment.Center;
					paraphStyle.MinimumLineHeight = 38;
					paraphStyle.MaximumLineHeight = 38;

					var font = NSFont.FromFontName ("Myriad Set Semibold", 34) != null ? NSFont.FromFontName ("Myriad Set Semibold", 34) : NSFont.FromFontName ("Avenir Medium", 34);

					var shadow = new NSShadow ();
					shadow.ShadowOffset = new CGSize (0, -2);
					shadow.ShadowBlurRadius = 4;
					shadow.ShadowColor = NSColor.FromDeviceWhite (0.0f, 0.5f);

					titleAttributes = new NSMutableDictionary ();
					titleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					titleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					titleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					titleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);

					var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy ();
					centeredParaphStyle.Alignment = NSTextAlignment.Center;

					centeredTitleAttributes = new NSMutableDictionary ();
					centeredTitleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					centeredTitleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					centeredTitleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					centeredTitleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);
				}

				var attrString = new NSAttributedString (title, centered ? centeredTitleAttributes : titleAttributes);
				var textSize = attrString.Size;

				//check if we need two lines to draw the text
				var twoLines = title.Contains ("\n");
				if (!twoLines)
					twoLines = textSize.Width > frame.Size.Width && title.Contains (" ");

				//if so, we need to adjust the size to center vertically
				if (twoLines)
					textSize.Height += 38;

				if (!centered)
					drawFrame.Inflate (-15, 0);

				//center vertically
				var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f;
				var drawFrameHeight = drawFrame.Size.Height;
				drawFrame.Size = new CGSize (drawFrame.Size.Width, drawFrame.Size.Height - dy);
				attrString.DrawString (drawFrame);
			}

			texture.UnlockFocus ();

			//set the created image as the diffuse texture of our 3D box
			var front = SCNMaterial.Create ();
			front.Diffuse.Contents = texture;
			front.LocksAmbientWithDiffuse = true;

			//use a lighter color for the chamfer and sides
			var sides = SCNMaterial.Create ();
			sides.Diffuse.Contents = lightColor;
			node.Geometry.Materials = new SCNMaterial[] {
				front,
				sides,
				sides,
				sides,
				sides
			};

			return node;
		}
コード例 #18
0
        public PlotHandler()
        {
            Control = new DWSIM.UI.Desktop.Mac.PlotView();
            {
            };

            ContextMenu cmenu = new ContextMenu();

            var b1 = new ButtonMenuItem()
            {
                Text = "Copy"
            };

            cmenu.Items.Add(b1);

            b1.Click += (sender, e) =>
            {
                Console.WriteLine(sender.ToString());

                // Get the standard pasteboard
                var pasteboard = NSPasteboard.GeneralPasteboard;

                // Empty the current contents
                pasteboard.ClearContents();

                NSImage image = new NSImage(new CoreGraphics.CGSize(Control.Bounds.Width, Control.Bounds.Height));

                image.LockFocus();

                var ctx = NSGraphicsContext.CurrentContext.GraphicsPort;

                Control.Layer.RenderInContext(ctx);

                image.UnlockFocus();

                // Add the current image to the pasteboard
                pasteboard.WriteObjects(new NSImage[] { image });
            };

            var b4 = new ButtonMenuItem()
            {
                Text = "Save to File"
            };

            cmenu.Items.Add(b4);

            b4.Click += (sender, e) =>
            {
                Console.WriteLine(sender.ToString());

                var sfd = new SaveFileDialog();

                sfd.Title = "Save Chart to PNG";
                sfd.Filters.Add(new FileFilter("PNG File", new string[] { ".png" }));
                sfd.CurrentFilterIndex = 0;

                if (sfd.ShowDialog(this.Widget) == DialogResult.Ok)
                {
                    NSImage image = new NSImage(new CoreGraphics.CGSize(Control.Bounds.Width, Control.Bounds.Height));

                    image.LockFocus();

                    var ctx = NSGraphicsContext.CurrentContext.GraphicsPort;

                    Control.Layer.RenderInContext(ctx);

                    image.UnlockFocus();

                    var imageRep = new NSBitmapImageRep(image.AsTiff());
                    var pngData  = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);
                    pngData.Save(sfd.FileName, false);
                }
            };

            var b7 = new ButtonMenuItem()
            {
                Text = "Reset to Default View"
            };

            cmenu.Items.Add(b7);

            b7.Click += (sender, e) =>
            {
                Console.WriteLine(sender.ToString());
                Control.Model.ResetAllAxes();
                Control.Model.InvalidatePlot(false);
            };

            Control.RightMouseAction = () => {
                cmenu.Show(this.Widget);
            };
        }