Пример #1
0
        public static System.IO.Stream AsJpegStream(this PImage image, int quality = 80)
        {
#if __IOS__
            return(image.AsJPEG((nfloat)quality).AsStream());
#elif __MACOS__
            // todo: jpeg quality?
            var imageRep = new NSBitmapImageRep(image.AsTiff());
            return(imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg)
                   .AsStream());
#endif
        }
Пример #2
0
        static NSData AsEncodedBitmapData(NSImage image, NSBitmapImageFileType fileType)
        {
            if (image == null)
            {
                return(null);
            }

            image.LockFocus();
            var rect = new CGRect(0, 0, image.Size.Width, image.Size.Height);
            var rep  = new NSBitmapImageRep(rect);

            image.UnlockFocus();
            return(rep.RepresentationUsingTypeProperties(fileType, null));
        }
        public static NSData AsBmp(this NSImage target)
        {
            var representations = target.Representations();

            if (representations[0] is NSBitmapImageRep rep)
            {
                return(rep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Bmp, new NSMutableDictionary()));
            }

            var rect    = new CGRect();
            var cgImage = target.AsCGImage(ref rect, null, null);
            var bitmap  = new NSBitmapImageRep(cgImage);

            return(bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Bmp, new NSMutableDictionary()));
        }
        private void CreateImage(string filePath, string destinationFilePath, double width, double height)
        {
            var image    = new NSImage(filePath);
            var newImage = Resize(image, width, height);

            InvokeOnMainThread(() =>
            {
                var rep = new NSBitmapImageRep(newImage.AsTiff());
                var resizesImageData = rep.RepresentationUsingTypeProperties(Path.GetExtension(filePath) == ".png" ? NSBitmapImageFileType.Png : NSBitmapImageFileType.Jpeg);

                resizesImageData.Save(destinationFilePath, true);

                UpdateProgressBar();
            });
        }
Пример #5
0
        /// <summary>
        /// Tos the DS bitmap.
        /// </summary>
        /// <returns>The DS bitmap.</returns>
        /// <param name="Image">Image.</param>
        public static DSBitmap ToDSBitmap(this NSImage Image)
        {
            var aMem = new MemoryStream();

            CGRect rect    = CGRect.Empty;
            var    cgImage = Image.AsCGImage(ref rect, null, null);
            var    bitmap  = new NSBitmapImageRep(cgImage);

            bitmap.Size = Image.Size;

            var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, null);

            data.AsStream().CopyTo(aMem);

            return(new DSBitmap(aMem.ToArray()));
        }
Пример #6
0
        Bitmap GetBitmap()
        {
            var frame = (MacImageFrame)_frames[_currentFrame];

            if (frame.Bitmap != null)
            {
                return(frame.Bitmap);
            }

            SetValueForProperty(_rep, NSBitmapImageRep.CurrentFrame, new NSNumber(_currentFrame));

            var     frameData  = _rep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, null);
            NSImage frameImage = new NSImage(frameData);

            frame.Bitmap = new Bitmap(new global::Eto.Mac.Drawing.BitmapHandler(frameImage));
            return(frame.Bitmap);
        }
Пример #7
0
        private NSData CreateRepresentation(ImageFormat format = ImageFormat.Png, float quality = 1)
        {
            var previous = NSApplication.CheckForIllegalCrossThreadCalls;

            NSApplication.CheckForIllegalCrossThreadCalls = false;

            NSBitmapImageFileType type;
            NSDictionary          dictionary;

            switch (format)
            {
            case ImageFormat.Jpeg:
                type       = NSBitmapImageFileType.Jpeg;
                dictionary = new NSDictionary(new NSNumber(quality), AppKitConstants.NSImageCompressionFactor);
                break;

            case ImageFormat.Tiff:
                type       = NSBitmapImageFileType.Tiff;
                dictionary = new NSDictionary();
                break;

            case ImageFormat.Gif:
                type       = NSBitmapImageFileType.Gif;
                dictionary = new NSDictionary();
                break;

            case ImageFormat.Bmp:
                type       = NSBitmapImageFileType.Bmp;
                dictionary = new NSDictionary();
                break;

            default:
                type       = NSBitmapImageFileType.Png;
                dictionary = new NSDictionary();
                break;
            }

            var rect     = new CGRect();
            var cgimage  = _image.AsCGImage(ref rect, null, null);
            var imageRep = new NSBitmapImageRep(cgimage);
            var data     = imageRep.RepresentationUsingTypeProperties(type, dictionary);

            NSApplication.CheckForIllegalCrossThreadCalls = previous;

            return(data);
        }
Пример #8
0
        public ITexture GetTexture(string path)
        {
            if (path.IsNullOrWhiteSpace())
            {
                return(TexturePool.Instance.GetTexture(null));
            }
            FileAttributes attr        = File.GetAttributes(path);
            bool           isDirectory = (attr & FileAttributes.Directory) == FileAttributes.Directory;

            if (isDirectory && directoryTexture != null)
            {
                return(directoryTexture);
            }
            var ext = Path.GetExtension(path);

            if (ext == null)
            {
                return(TexturePool.Instance.GetTexture(null));
            }
            if (textureCache.ContainsKey(ext))
            {
                return(textureCache[ext]);
            }
            var icon = NSWorkspace.SharedWorkspace.IconForFileType(isDirectory ? NSFileTypeForHFSTypeCode.FinderIcon : ext);

            using (var stream = new MemoryStream())
                using (var representation = new NSBitmapImageRep(icon.CGImage)) {
                    NSData data = null;
                    data = representation.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);            //, new NSDictionary());
                    using (var bitmapStream = data.AsStream()) {
                        bitmapStream.CopyTo(stream);
                    }
                    data.Dispose();
                    var texture = new Texture2D();
                    texture.LoadImage(stream);
                    if (isDirectory)
                    {
                        directoryTexture = texture;
                    }
                    else
                    {
                        textureCache.Add(ext, texture);
                    }
                    return(texture);
                }
        }
Пример #9
0
        /// <summary>
        /// Saves an image as a jpeg image, with the given quality
        /// </summary>
        /// <param name="path">Path to which the image would be saved.</param>
        /// <param name="quality">An integer from 0 to 100, with 100 being the highest quality</param>
        public static void SaveJpeg(string path, NSImage img, int quality)
        {
            if (quality < 0 || quality > 100)
            {
                throw new ArgumentOutOfRangeException(nameof(quality), quality, "quality must be between 0 and 100.");
            }

            var    tiffData   = img.AsTiff();
            var    imgRep     = new NSBitmapImageRep(tiffData);
            double doubleQual = quality;
            var    settings   = new NSMutableDictionary
            {
                { NSBitmapImageRep.FallbackBackgroundColor, NSColor.White },
                { NSBitmapImageRep.CompressionFactor, new NSNumber(doubleQual / 100) }
            };
            var imgData = imgRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, settings);

            File.WriteAllBytes(path, imgData.ToArray());
        }
Пример #10
0
        protected override void UpdateCapturedImage()
        {
            if (view != null && layer == null)
            {
                var bitmap = view.BitmapImageRepForCachingDisplayInRect(view.Bounds);
                if (bitmap == null)
                {
                    return;
                }

                view.CacheDisplay(view.Bounds, bitmap);
                var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);
                CapturedImage = data.ToArray();
            }
            else if (layer != null)
            {
                var  scale       = layer.ContentsScale;
                nint h           = (nint)(layer.Bounds.Height * scale);
                nint w           = (nint)(layer.Bounds.Width * scale);
                nint bytesPerRow = w * 4;

                if (h <= 0 || w <= 0)
                {
                    return;
                }

                using (var colorSpace = CGColorSpace.CreateGenericRgb())
                    using (var context = new CGBitmapContext(IntPtr.Zero, w, h, 8, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedLast)) {
                        // Apply a flipping transform because layers are apparently weird.
                        var transform = new CGAffineTransform(scale, 0, 0, -scale, 0, h);
                        context.ConcatCTM(transform);

                        layer.RenderInContext(context);

                        using (var image = context.ToImage())
                            using (var bitmap = new NSBitmapImageRep(image)) {
                                var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);
                                CapturedImage = data.ToArray();
                            }
                    }
            }
        }
Пример #11
0
        void Button_Activated(object sender, EventArgs e)
        {
            var image = new NSImage(new CGSize(300, 100));

            image.LockFocus();
            var path = NSBezierPath.FromOvalInRect(new CGRect(new CGPoint(0, 0), new CGSize(300, 100)));

            NSColor.Red.Set();
            path.Fill();
            image.UnlockFocus();

            var bmprep = new NSBitmapImageRep(image.CGImage);
            var data   = bmprep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Bmp);
            var bitmap = new Bitmap(data.AsStream());

            var folder   = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            var filename = System.IO.Path.Combine(folder, "test.bmp");

            bitmap.Save(filename);
        }
Пример #12
0
        public Task Save(CompressedBitmapFormat format, float quality, Stream target)
        {
            return(Task.Run(() => {
                #if UIKIT
                var data = format == CompressedBitmapFormat.Jpeg ? inner.AsJPEG((float)quality) : inner.AsPNG();
                data.AsStream().CopyTo(target);
                #else
                var rect = new RectangleF();
                var cgImage = inner.AsCGImage(ref rect, null, null);
                var imageRep = new NSBitmapImageRep(cgImage);

                var props = format == CompressedBitmapFormat.Png ?
                            new NSDictionary() :
                            new NSDictionary(new NSNumber(quality), new NSString("NSImageCompressionFactor"));

                var type = format == CompressedBitmapFormat.Png ? NSBitmapImageFileType.Png : NSBitmapImageFileType.Jpeg;

                var outData = imageRep.RepresentationUsingTypeProperties(type, props);
                outData.AsStream().CopyTo(target);
                #endif
            }));
        }
Пример #13
0
        public static byte[] PixelToJpeg(byte[] rawPixel, int width, int height, int channels)
        {
#if __ANDROID__
            if (channels != 4)
            {
                throw new NotImplementedException("Only 4 channel pixel input is supported.");
            }
            using (Bitmap bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888))
                using (MemoryStream ms = new MemoryStream())
                {
                    IntPtr ptr = bitmap.LockPixels();
                    //GCHandle handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
                    Marshal.Copy(rawPixel, 0, ptr, rawPixel.Length);

                    bitmap.UnlockPixels();

                    bitmap.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                    return(ms.ToArray());
                }
#elif __IOS__
            if (channels != 3)
            {
                throw new NotImplementedException("Only 3 channel pixel input is supported.");
            }
            System.Drawing.Size sz     = new System.Drawing.Size(width, height);
            GCHandle            handle = GCHandle.Alloc(rawPixel, GCHandleType.Pinned);
            using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                using (CGBitmapContext context = new CGBitmapContext(
                           handle.AddrOfPinnedObject(),
                           sz.Width, sz.Height,
                           8,
                           sz.Width * 3,
                           cspace,
                           CGImageAlphaInfo.PremultipliedLast))
                    using (CGImage cgImage = context.ToImage())
                        using (UIImage newImg = new UIImage(cgImage))
                        {
                            handle.Free();
                            var    jpegData = newImg.AsJPEG();
                            byte[] raw      = new byte[jpegData.Length];
                            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, raw, 0,
                                                                        (int)jpegData.Length);
                            return(raw);
                        }
#elif __UNIFIED__ //OSX
            if (channels != 4)
            {
                throw new NotImplementedException("Only 4 channel pixel input is supported.");
            }
            System.Drawing.Size sz = new System.Drawing.Size(width, height);

            using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB())
                using (CGBitmapContext context = new CGBitmapContext(
                           rawPixel,
                           sz.Width, sz.Height,
                           8,
                           sz.Width * 4,
                           cspace,
                           CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big))
                    using (CGImage cgImage = context.ToImage())

                        using (NSBitmapImageRep newImg = new NSBitmapImageRep(cgImage))
                        {
                            var jpegData = newImg.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg);

                            byte[] raw = new byte[jpegData.Length];
                            System.Runtime.InteropServices.Marshal.Copy(jpegData.Bytes, raw, 0,
                                                                        (int)jpegData.Length);
                            return(raw);
                        }
#else
            throw new NotImplementedException("PixelToJpeg Not Implemented in this platform");
#endif
        }
Пример #14
0
        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);
        }
Пример #15
0
        /// <summary>
        /// Saves the specified color data as an image with the specified format.
        /// </summary>
        private void Save(Color[] data, Int32 width, Int32 height, Stream stream, Boolean asPng)
        {
            using (var rep = new NSBitmapImageRep(IntPtr.Zero, width, height, 8, 4, true, false, "NSCalibratedRGBColorSpace", 0, 0))
            {
                fixed (Color* pData = data)
                {
                    for (int y = 0; y < height; y++)
                    {
                        var pSrc = pData + (y * width);
                        var pDst = (Byte*)rep.BitmapData + (y * rep.BytesPerRow);

                        for (int x = 0; x < width; x++)
                        {
                            var color = *pSrc++;
                            *pDst++ = color.R;
                            *pDst++ = color.G;
                            *pDst++ = color.B;
                            *pDst++ = color.A;
                        }
                    }
                }

                var filetype = asPng ? NSBitmapImageFileType.Png : NSBitmapImageFileType.Jpeg;
                var properties = new NSDictionary();

                using (var imgData = rep.RepresentationUsingTypeProperties(filetype, properties))
                {
                    using (var imgStream = imgData.AsStream())
                    {
                        imgStream.CopyTo(stream);
                    }
                }
            }
        }
Пример #16
0
		NSData ImageAsJPEG (NSImage i)
		{
			NSData d = i.AsTiff ();
			NSBitmapImageRep rep = new NSBitmapImageRep (d);
			return rep.RepresentationUsingTypeProperties (NSBitmapImageFileType.Jpeg, NSDictionary.FromObjectAndKey (NSNumber.FromInt32 (1), NSBitmapImageRep.CompressionFactor));
		}
Пример #17
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);
            };
        }
Пример #18
0
        static string RenderSize(XIR.Size size)
        {
            var base64 = string.Empty;

            // We want the absolute values of the size
            var workSize = new CGSize(Math.Abs(size.Width), Math.Abs(size.Height));

            // This is our scale factor for output
            var dstSize = new CGSize(50, 50);

            // Define our Height label variables
            var numHeightLabelBounds = CGSize.Empty;
            var heightLabelBounds    = CGSize.Empty;
            var heightBounds         = CGSize.Empty;

            // Obtain our label lines and bounding boxes of the labels
            var numHeightLine = GetLabel(string.Format("{0:0.########}", size.Height), out numHeightLabelBounds);
            var heightLine    = GetSubLabel("Height", out heightLabelBounds);

            heightBounds.Width  = NMath.Max(numHeightLabelBounds.Width, heightLabelBounds.Width);
            heightBounds.Height = NMath.Max(numHeightLabelBounds.Height, heightLabelBounds.Height);


            // Define our Width label variables
            var numWidthLabelBounds = CGSize.Empty;
            var widthLabelBounds    = CGSize.Empty;
            var widthBounds         = CGSize.Empty;

            // Obtain our label lines and bound boxes of the labels
            var numWidthLine = GetLabel(string.Format("{0:0.########}", size.Width), out numWidthLabelBounds);
            var widthLine    = GetSubLabel("Width", out widthLabelBounds);

            widthBounds.Width  = NMath.Max(numWidthLabelBounds.Width, widthLabelBounds.Width);
            widthBounds.Height = NMath.Max(numWidthLabelBounds.Height, widthLabelBounds.Height);

            // Calculate our scale based on our destination size
            var ratio = 1f;

            if (workSize.Width > workSize.Height)
            {
                ratio          = (float)workSize.Height / (float)workSize.Width;
                dstSize.Height = (int)(dstSize.Height * ratio);
            }
            else
            {
                ratio         = (float)workSize.Width / (float)workSize.Height;
                dstSize.Width = (int)(dstSize.Width * ratio);
            }

            // Make sure we at least have something to draw if the values are very small
            dstSize.Width  = NMath.Max(dstSize.Width, 4f);
            dstSize.Height = NMath.Max(dstSize.Height, 4f);

            // Define graphic element sizes and offsets
            const int   lineWidth       = 2;
            const float capSize         = 8f;
            const float vCapIndent      = 3f;
            const float separationSpace = 2f;

            var extraBoundingSpaceWidth  = (widthBounds.Width + separationSpace) * 2;
            var extraBoundingSpaceHeight = (heightBounds.Height + separationSpace) * 2;

            int width  = (int)(dstSize.Width + lineWidth + capSize + vCapIndent + extraBoundingSpaceWidth);
            int height = (int)(dstSize.Height + lineWidth + capSize + extraBoundingSpaceHeight);

            var bytesPerRow = 4 * width;

            using (var context = new CGBitmapContext(
                       IntPtr.Zero, width, height,
                       8, bytesPerRow, CGColorSpace.CreateDeviceRGB(),
                       CGImageAlphaInfo.PremultipliedFirst))
            {
                // Clear the context with our background color
                context.SetFillColor(BackgroundColor.CGColor);
                context.FillRect(new CGRect(0, 0, width, height));

                // Setup our matrices so our 0,0 is top left corner.  Just makes it easier to layout
                context.ConcatCTM(context.GetCTM().Invert());
                var matrix = new CGAffineTransform(
                    1, 0, 0, -1, 0, height);

                context.ConcatCTM(matrix);

                context.SetStrokeColor(pen.CGColor);
                context.SetLineWidth(lineWidth);

                context.SaveState();

                // We need to offset the drawing of our size segment rulers leaving room for labels
                var xOffSet = heightBounds.Width;
                var yOffset = (height - extraBoundingSpaceHeight) / 2f - dstSize.Height / 2f;

                context.TranslateCTM(xOffSet, yOffset);

                // Draw the Height segment ruler
                var vCapCenter = vCapIndent + (capSize / 2f);

                context.AddLines(new CGPoint[] { new CGPoint(vCapIndent, 1), new CGPoint(vCapIndent + capSize, 1),
                                                 new CGPoint(vCapCenter, 1), new CGPoint(vCapCenter, dstSize.Height),
                                                 new CGPoint(vCapIndent, dstSize.Height), new CGPoint(vCapIndent + capSize, dstSize.Height), });


                // Draw the Width segment ruler
                var hCapIndent  = vCapIndent + capSize + separationSpace;
                var hCapOffsetY = dstSize.Height;
                var hCapCenter  = hCapOffsetY + (capSize / 2f);
                context.AddLines(new CGPoint[] { new CGPoint(hCapIndent, hCapOffsetY), new CGPoint(hCapIndent, hCapOffsetY + capSize),
                                                 new CGPoint(hCapIndent, hCapCenter), new CGPoint(hCapIndent + dstSize.Width, hCapCenter),
                                                 new CGPoint(hCapIndent + dstSize.Width, hCapOffsetY), new CGPoint(hCapIndent + dstSize.Width, hCapOffsetY + capSize), });

                context.StrokePath();

                context.RestoreState();

                // Setup our text matrix
                var textMatrix = new CGAffineTransform(
                    1, 0, 0, -1, 0, 0);

                context.TextMatrix = textMatrix;


                // Draw the Height label
                context.TextPosition = new CGPoint(heightBounds.Width / 2 - numHeightLabelBounds.Width / 2, height / 2 - heightBounds.Height / 2);
                numHeightLine.Draw(context);

                context.TextPosition = new CGPoint(heightBounds.Width / 2 - heightLabelBounds.Width / 2, height / 2 + heightBounds.Height / 2);
                heightLine.Draw(context);


                // Draw the Width label
                var widthOffsetX = heightBounds.Width - separationSpace + dstSize.Width / 2;
                context.TextPosition = new CGPoint(widthOffsetX + (widthBounds.Width / 2 - numWidthLabelBounds.Width / 2), height - widthBounds.Height - 2);
                numWidthLine.Draw(context);

                context.TextPosition = new CGPoint(widthOffsetX + (widthBounds.Width / 2 - widthLabelBounds.Width / 2), height - widthLabelBounds.Height / 2);
                widthLine.Draw(context);

                // Get rid of our lines
                numHeightLine.Dispose();
                heightLine.Dispose();

                numWidthLine.Dispose();
                widthLine.Dispose();

                // Convert to base64 for display
                var bitmap = new NSBitmapImageRep(context.ToImage());

                var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);
                base64 = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
            }

            return(String.Format("" +
                                 "<figure>" +
                                 "<figcaption>" +
                                 "Size: " +
                                 "<span class='var'>Width</span> = <span class='value'>{0:0.########}</span>, " +
                                 "<span class='var'>Height</span> = <span class='value'>{1:0.########}</span>" +
                                 "</figcaption>" +
                                 "<img width='{2}' height='{3}' src='data:image/png;base64,{4}' />" +
                                 "</figure>",
                                 size.Width, size.Height,
                                 (int)width,
                                 (int)height,
                                 base64
                                 ));
        }
        public virtual async Task <Tuple <Stream, LoadingResult, ImageInformation> > Resolve(string identifier, TaskParameter parameters, CancellationToken token)
        {
            NSBundle bundle       = null;
            var      filename     = Path.GetFileNameWithoutExtension(identifier);
            var      tmpPath      = Path.GetDirectoryName(identifier).Trim('/');
            var      filenamePath = string.IsNullOrWhiteSpace(tmpPath) ? null : tmpPath + "/";

            foreach (var fileType in fileTypes)
            {
                string file      = null;
                var    extension = Path.HasExtension(identifier) ? Path.GetExtension(identifier) : string.IsNullOrWhiteSpace(fileType) ? string.Empty : "." + fileType;

                token.ThrowIfCancellationRequested();

                int scale = (int)ScaleHelper.Scale;
                if (scale > 1)
                {
                    while (scale > 1)
                    {
                        token.ThrowIfCancellationRequested();

                        var tmpFile = string.Format("{0}@{1}x{2}", filename, scale, extension);
                        bundle = NSBundle._AllBundles.FirstOrDefault(bu =>
                        {
                            var path = string.IsNullOrWhiteSpace(filenamePath) ?
                                       bu.PathForResource(tmpFile, null) :
                                       bu.PathForResource(tmpFile, null, filenamePath);
                            return(!string.IsNullOrWhiteSpace(path));
                        });

                        if (bundle != null)
                        {
                            file = tmpFile;
                            break;
                        }
                        scale--;
                    }
                }

                token.ThrowIfCancellationRequested();

                if (file == null)
                {
                    var tmpFile = string.Format(filename + extension);
                    file   = tmpFile;
                    bundle = NSBundle._AllBundles.FirstOrDefault(bu =>
                    {
                        var path = string.IsNullOrWhiteSpace(filenamePath) ?
                                   bu.PathForResource(tmpFile, null) :
                                   bu.PathForResource(tmpFile, null, filenamePath);

                        return(!string.IsNullOrWhiteSpace(path));
                    });
                }

                token.ThrowIfCancellationRequested();

                if (bundle != null)
                {
                    string path = !string.IsNullOrEmpty(filenamePath) ? bundle.PathForResource(file, null, filenamePath) : bundle.PathForResource(file, null);

                    var stream           = FileStore.GetInputStream(path, true);
                    var imageInformation = new ImageInformation();
                    imageInformation.SetPath(identifier);
                    imageInformation.SetFilePath(path);

                    return(new Tuple <Stream, LoadingResult, ImageInformation>(
                               stream, LoadingResult.CompiledResource, imageInformation));
                }

                token.ThrowIfCancellationRequested();

                if (string.IsNullOrEmpty(fileType))
                {
                    //Asset catalog
                    NSDataAsset asset = null;

                    try
                    {
                        await MainThreadDispatcher.Instance.PostAsync(() => asset = new NSDataAsset(filename)).ConfigureAwait(false);
                    }
                    catch (Exception) { }

                    if (asset != null)
                    {
                        token.ThrowIfCancellationRequested();
                        var stream           = asset.Data?.AsStream();
                        var imageInformation = new ImageInformation();
                        imageInformation.SetPath(identifier);
                        imageInformation.SetFilePath(null);

                        return(new Tuple <Stream, LoadingResult, ImageInformation>(
                                   stream, LoadingResult.CompiledResource, imageInformation));
                    }


                    NSImage image = null;

                    try
                    {
                        await MainThreadDispatcher.Instance.PostAsync(() => image = NSImage.ImageNamed(filename)).ConfigureAwait(false);
                    }
                    catch (Exception) { }

                    if (image != null)
                    {
                        token.ThrowIfCancellationRequested();
                        var imageRep = new NSBitmapImageRep(image.AsTiff());
                        var stream   = imageRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png)
                                       .AsStream();
                        //var stream = image.AsPNG()?.AsStream();
                        var imageInformation = new ImageInformation();
                        imageInformation.SetPath(identifier);
                        imageInformation.SetFilePath(null);

                        return(new Tuple <Stream, LoadingResult, ImageInformation>(
                                   stream, LoadingResult.CompiledResource, imageInformation));
                    }
                }
            }

            throw new FileNotFoundException(identifier);
        }
Пример #20
0
        static string RenderPoint(XIR.Point point)
        {
            var base64 = string.Empty;

            var pointSize = new CGSize(8, 8);
            var rectangle = new CGRect(0, 0, 100, 100);

            var measure = CGSize.Empty;

            var line = GetLabel(string.Format("({0:0.########}, {1:0.###########})", point.X, point.Y), out measure);

            if (measure.Width > rectangle.Width)
            {
                rectangle.Size = new CGSize(measure.Width, measure.Width);
            }

            int width  = (int)rectangle.Width;
            int height = (int)rectangle.Height;

            var bytesPerRow = 4 * width;

            using (var context = new CGBitmapContext(
                       IntPtr.Zero, width, height,
                       8, bytesPerRow, CGColorSpace.CreateDeviceRGB(),
                       CGImageAlphaInfo.PremultipliedFirst))
            {
                context.SetFillColor(BackgroundColor.CGColor);
                context.FillRect(rectangle);


                context.SetFillColor(pen.CGColor);
                var centerX = rectangle.GetMidX() - pointSize.Width / 2;
                var centerY = rectangle.GetMidY() - pointSize.Height / 2;
                context.FillEllipseInRect(new CGRect(centerX, centerY, pointSize.Width, pointSize.Height));

                context.ConcatCTM(context.GetCTM().Invert());
                var matrix = new CGAffineTransform(
                    1, 0, 0, -1, 0, height);

                context.ConcatCTM(matrix);
                var textMatrix = new CGAffineTransform(
                    1, 0, 0, -1, 0, 0);

                context.TextMatrix = textMatrix;

                context.TextPosition = new CGPoint(rectangle.GetMidX() - measure.Width / 2, rectangle.GetMidY() - (measure.Height * 2));

                line.Draw(context);
                line.Dispose();

                line = GetSubLabel("x, y", out measure);
                context.TextPosition = new CGPoint(rectangle.GetMidX() - measure.Width / 2, rectangle.GetMidY() - (measure.Height));

                line.Draw(context);
                line.Dispose();

                var bitmap = new NSBitmapImageRep(context.ToImage());

                var data = bitmap.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png);
                base64 = data.GetBase64EncodedString(NSDataBase64EncodingOptions.None);
            }

            return(String.Format(
                       "<figure>" +
                       "<figcaption>" +
                       "Point: " +
                       "<span class='var'>X</span> = <span class='value'>{0:0.########}</span>, " +
                       "<span class='var'>Y</span> = <span class='value'>{1:0.########}</span>" +
                       "</figcaption>" +
                       "<img width='{2}' height='{3}' src='data:image/png;base64,{4}' />" +
                       "</figure>",
                       point.X, point.Y,
                       (int)rectangle.Width,
                       (int)rectangle.Height,
                       base64
                       ));
        }