Esempio n. 1
0
        public static NativeImage ToMultiResolutionImage(this IDrawable drawable, int width, int height)
        {
            if (drawable == null)
            {
                return(null);
            }

            var normalImage       = drawable.ToImage(width, height);
            var normalNativeImage = normalImage.AsNSImage();
            var normalImageData   = normalNativeImage.AsTiff();
            var normalImageRep    = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(normalImageData);

            var retinaImage       = drawable.ToImage(width * 2, height * 2, 2);
            var retinaNativeImage = retinaImage.AsNSImage();
            var retinaImageData   = retinaNativeImage.AsTiff();
            var retinaImageRep    = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(retinaImageData);

            var combinedImage = new NSImage {
                MatchesOnMultipleResolution = true
            };

            combinedImage.AddRepresentations(new NSImageRep[] { normalImageRep, retinaImageRep });

            return(new NativeImage(combinedImage));
        }
Esempio n. 2
0
 public static Image ToImage(this NSImage img)
 {
     using (var imageData = img.AsTiff()) {
         var imgRep     = NSBitmapImageRep.ImageRepFromData(imageData) as NSBitmapImageRep;
         var imageProps = new NSDictionary();
         var data       = imgRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, imageProps);
         return(Image.FromStream(data.AsStream()));
     }
 }
Esempio n. 3
0
        public override object CreateImage(object backend)
        {
            var gc        = (CGContextBackend)backend;
            var img       = new NSImage(((CGBitmapContext)gc.Context).ToImage(), gc.Size);
            var imageData = img.AsTiff();
            var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
            var im        = new NSImage();

            im.AddRepresentation(imageRep);
            return(im);
        }
Esempio n. 4
0
        public override object RenderWidget(Widget w)
        {
            var view = ((ViewBackend)w.GetBackend()).Widget;

            view.LockFocus();
            var img       = new NSImage(view.DataWithPdfInsideRect(view.Bounds));
            var imageData = img.AsTiff();
            var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
            var im        = new NSImage();

            im.AddRepresentation(imageRep);
            im.Size = new CGSize((nfloat)view.Bounds.Width, (nfloat)view.Bounds.Height);
            return(im);
        }
Esempio n. 5
0
        public override object ConvertToBitmap(object handle, int pixelWidth, int pixelHeight, ImageFormat format)
        {
            if (handle is CustomImage)
            {
                var flags = CGBitmapFlags.ByteOrderDefault;
                int bytesPerRow;
                switch (format)
                {
                case ImageFormat.ARGB32:
                    bytesPerRow = pixelWidth * 4;
                    flags      |= CGBitmapFlags.PremultipliedFirst;
                    break;

                case ImageFormat.RGB24:
                    bytesPerRow = pixelWidth * 3;
                    flags      |= CGBitmapFlags.None;
                    break;

                default:
                    throw new NotImplementedException("ImageFormat: " + format.ToString());
                }

                var bmp = new CGBitmapContext(IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags);
                bmp.TranslateCTM(0, pixelHeight);
                bmp.ScaleCTM(1, -1);

                var ctx = new CGContextBackend {
                    Context = bmp,
                    Size    = new SizeF(pixelWidth, pixelHeight),
                    InverseViewTransform = bmp.GetCTM().Invert()
                };

                var ci = (CustomImage)handle;
                ci.DrawInContext(ctx);

                var img       = new NSImage(((CGBitmapContext)bmp).ToImage(), new SizeF(pixelWidth, pixelHeight));
                var imageData = img.AsTiff();
                var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
                var im        = new NSImage();
                im.AddRepresentation(imageRep);
                return(im);
            }
            else
            {
                return(handle);
            }
        }
Esempio n. 6
0
        public override void SaveToStream(object backend, System.IO.Stream stream, ImageFileType fileType)
        {
            NSImage img = backend as NSImage;

            if (img == null)
            {
                throw new NotSupportedException();
            }

            var imageData = img.AsTiff();
            var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
            var props     = new NSDictionary();

            imageData = imageRep.RepresentationUsingTypeProperties(fileType.ToMacFileType(), props);
            using (var s = imageData.AsStream()) {
                s.CopyTo(stream);
            }
        }
Esempio n. 7
0
        public static void SaveToFile(this NSImage image, string path)
        {
            //NSBitmapImageRep *imgRep = [[image representations] objectAtIndex: 0];
            //NSData *data = [imgRep representationUsingType: NSPNGFileType properties: nil];
            //[data writeToFile: @"/path/to/file.png" atomically: NO];

            var imageData  = image.AsTiff();
            var imgRep     = NSBitmapImageRep.ImageRepFromData(imageData) as NSBitmapImageRep;
            var imageProps = new NSDictionary();

            var data = imgRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, imageProps);

            NSError error;

            data.Save(path, false, out error);

            data.Dispose();
            imgRep.Dispose();
        }
Esempio n. 8
0
        public override object ConvertToBitmap(ImageDescription idesc, double scaleFactor, ImageFormat format)
        {
            double width       = idesc.Size.Width;
            double height      = idesc.Size.Height;
            int    pixelWidth  = (int)(width * scaleFactor);
            int    pixelHeight = (int)(height * scaleFactor);

            if (idesc.Backend is CustomImage)
            {
                var flags = CGBitmapFlags.ByteOrderDefault;
                int bytesPerRow;
                switch (format)
                {
                case ImageFormat.ARGB32:
                    bytesPerRow = pixelWidth * 4;
                    flags      |= CGBitmapFlags.PremultipliedFirst;
                    break;

                case ImageFormat.RGB24:
                    bytesPerRow = pixelWidth * 3;
                    flags      |= CGBitmapFlags.None;
                    break;

                default:
                    throw new NotImplementedException("ImageFormat: " + format.ToString());
                }

                var bmp = new CGBitmapContext(IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags);
                bmp.TranslateCTM(0, pixelHeight);
                bmp.ScaleCTM((float)scaleFactor, (float)-scaleFactor);

                var ctx = new CGContextBackend {
                    Context = bmp,
                    Size    = new CGSize((nfloat)width, (nfloat)height),
                    InverseViewTransform = bmp.GetCTM().Invert(),
                    ScaleFactor          = scaleFactor
                };

                var ci = (CustomImage)idesc.Backend;
                ci.DrawInContext(ctx, idesc);

                var img       = new NSImage(((CGBitmapContext)bmp).ToImage(), new CGSize(pixelWidth, pixelHeight));
                var imageData = img.AsTiff();
                var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
                var im        = new NSImage();
                im.AddRepresentation(imageRep);
                im.Size = new CGSize((nfloat)width, (nfloat)height);
                bmp.Dispose();
                return(im);
            }
            else
            {
                NSImage          img    = (NSImage)idesc.Backend;
                NSBitmapImageRep bitmap = img.Representations().OfType <NSBitmapImageRep> ().FirstOrDefault();
                if (bitmap == null)
                {
                    var imageData = img.AsTiff();
                    var imageRep  = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData);
                    var im        = new NSImage();
                    im.AddRepresentation(imageRep);
                    im.Size = new CGSize((nfloat)width, (nfloat)height);
                    return(im);
                }
                return(idesc.Backend);
            }
        }
Esempio n. 9
0
        private static DataPackageView GetFromNative(NSPasteboard pasteboard)
        {
            if (pasteboard is null)
            {
                throw new ArgumentException(nameof(pasteboard));
            }

            var dataPackage = new DataPackage();

            // Extract all the standard data format information from the pasteboard items.
            // Each format can only be used once; therefore, generally the last occurrence of the format will be the one used.
            foreach (NSPasteboardItem item in pasteboard.PasteboardItems)
            {
                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeTIFF) ||
                    item.Types.Contains(NSPasteboard.NSPasteboardTypePNG))
                {
                    // Images may be very large, we never want to load them until they are needed.
                    // Therefore, create a data provider used to asynchronously fetch the image.
                    dataPackage.SetDataProvider(
                        StandardDataFormats.Bitmap,
                        async cancellationToken =>
                    {
                        NSImage?image = null;

                        /* Some apps, including Photos, don't appear to put image data in the pasteboard.
                         * Instead, the image URL is provided although the type indicates it is an image.
                         *
                         * To get around this an image is read as follows:
                         *   (1) If the pasteboard contains an image type then:
                         *   (2) Attempt to read the image as an object (NSImage).
                         *       This may fail as some tested apps provide a URL although declare an image (Photos).
                         *       With other apps (such as web browsers) an image will be read correctly here.
                         *   (3) If reading as an NSImage object fails, attempt to read the image from a file URL (local images)
                         *   (4) If reading from a file URL fails, attempt to read the image from a URL (remote images)
                         *
                         * Reading as an NSImage object follows the docs here:
                         *   https://docs.microsoft.com/en-us/xamarin/mac/app-fundamentals/copy-paste#add-an-nsdocument
                         */

                        var classArray = new Class[] { new Class("NSImage") };
                        if (pasteboard.CanReadObjectForClasses(classArray, null))
                        {
                            NSObject[] objects = pasteboard.ReadObjectsForClasses(classArray, null);

                            if (objects.Length > 0)
                            {
                                // Only use the first image found
                                image = objects[0] as NSImage;
                            }
                        }

                        // In order to get here the pasteboard must have declared it had image types.
                        // However, if image is null, no objects were found and the image is likely a URL instead.
                        if (image == null &&
                            item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl))
                        {
                            var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl);
                            image   = new NSImage(new NSUrl(url));
                        }

                        if (image == null &&
                            item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl))
                        {
                            var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl);
                            image   = new NSImage(new NSUrl(url));
                        }

                        if (image != null)
                        {
                            // Thanks to: https://stackoverflow.com/questions/13305028/monomac-best-way-to-convert-bitmap-to-nsimage/13355747
                            using (var imageData = image.AsTiff())
                            {
                                var imgRep = NSBitmapImageRep.ImageRepFromData(imageData) as NSBitmapImageRep;
                                var data   = imgRep !.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, null);

                                return(new RandomAccessStreamReference(async ct =>
                                {
                                    return data.AsStream().AsRandomAccessStream().TrySetContentType("image/png");
                                }));
                            }
                        }
                        else
                        {
                            // Return an empty image
                            return(new RandomAccessStreamReference(async ct =>
                            {
                                var stream = new MemoryStream();
                                stream.Position = 0;

                                return stream.AsRandomAccessStream().TrySetContentType("image/png");
                            }));
                        }
                    });
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeHTML))
                {
                    var html = item.GetStringForType(NSPasteboard.NSPasteboardTypeHTML);
                    if (html != null)
                    {
                        dataPackage.SetHtmlFormat(html);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeRTF))
                {
                    var rtf = item.GetStringForType(NSPasteboard.NSPasteboardTypeRTF);
                    if (rtf != null)
                    {
                        dataPackage.SetRtf(rtf);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeFileUrl))
                {
                    // Drag and drop will use temporary URLs similar to: file:///.file/id=1234567.1234567
                    var tempFileUrl = item.GetStringForType(NSPasteboard.NSPasteboardTypeFileUrl);

                    // Files may be very large, we never want to load them until they are needed.
                    // Therefore, create a data provider used to asynchronously fetch the file.
                    dataPackage.SetDataProvider(
                        StandardDataFormats.StorageItems,
                        async cancellationToken =>
                    {
                        // Convert from a temp Url (see above example) into an absolute file path
                        var fileUrl = new NSUrl(tempFileUrl);
                        var file    = await StorageFile.GetFileFromPathAsync(fileUrl.FilePathUrl.AbsoluteString);

                        var storageItems = new List <IStorageItem>();
                        storageItems.Add(file);

                        return(storageItems.AsReadOnly());
                    });
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeString))
                {
                    var text = item.GetStringForType(NSPasteboard.NSPasteboardTypeString);
                    if (text != null)
                    {
                        dataPackage.SetText(text);
                    }
                }

                if (item.Types.Contains(NSPasteboard.NSPasteboardTypeUrl))
                {
                    var url = item.GetStringForType(NSPasteboard.NSPasteboardTypeUrl);
                    if (url != null)
                    {
                        DataPackage.SeparateUri(
                            url,
                            out string?webLink,
                            out string?applicationLink);

                        if (webLink != null)
                        {
                            dataPackage.SetWebLink(new Uri(webLink));
                        }

                        if (applicationLink != null)
                        {
                            dataPackage.SetApplicationLink(new Uri(applicationLink));
                        }

                        // Deprecated but still added for compatibility
                        dataPackage.SetUri(new Uri(url));
                    }
                }
            }

            return(dataPackage.GetView());
        }