示例#1
0
 public static NSImage GetManifestImageResource(Assembly assembly, string resource)
 {
     if (assembly == null)
     {
         //TODO: not safe
         assembly = Assembly.GetEntryAssembly();
     }
     try
     {
         //TODO: not safe
         var fullResourceName = string.Concat(assembly.GetName().Name, ".Resources.", resource);
         //var resources = assembly.GetManifestResourceNames();
         using (var stream = assembly.GetManifestResourceStream(fullResourceName))
         {
             return(NSImage.FromStream(stream));
         }
     }
     catch (System.ArgumentNullException)
     {
         Console.WriteLine("[ERROR] File '{0}' not found in Resources and/or not set Build action to EmbeddedResource", resource);
     }
     catch (System.Exception ex)
     {
         Console.WriteLine(ex);
     }
     return(null);
 }
示例#2
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NSImageView imgV = new NSImageView();

            this.View.AddSubview(imgV);

            imgV.Frame = this.View.Bounds;

            var bmp = new ARGB32WinBitmap(200, 200);

            for (uint i = 0; i < 200; i++)
            {
                for (uint j = 0; j < 200; j++)
                {
                    bmp.PutPixel(i, j, (i > 20 && i < 50) ? ARGB32.Black : ARGB32.White);
                }
            }

            using (var stream = bmp.OutputStream())
            {
                imgV.Image = NSImage.FromStream(stream);
            }

            imgV.ImageScaling = NSImageScale.AxesIndependently;
        }
示例#3
0
        private NSImage GetIcon(Duplicati.GUI.TrayIcon.TrayIcons icon)
        {
            if (!m_images.ContainsKey(icon))
            {
                switch (icon)
                {
                case Duplicati.GUI.TrayIcon.TrayIcons.IdleError:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_ERROR));
                    break;

                case Duplicati.GUI.TrayIcon.TrayIcons.Paused:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_PAUSED));
                    break;

                case Duplicati.GUI.TrayIcon.TrayIcons.PausedError:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_PAUSED));
                    break;

                case Duplicati.GUI.TrayIcon.TrayIcons.Running:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_RUNNING));
                    break;

                case Duplicati.GUI.TrayIcon.TrayIcons.RunningError:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_RUNNING));
                    break;

                case Duplicati.GUI.TrayIcon.TrayIcons.Idle:
                default:
                    m_images[icon] = NSImage.FromStream(ASSEMBLY.GetManifestResourceStream(ICON_NORMAL));
                    break;
                }
            }

            return(m_images[icon]);
        }
示例#4
0
        private void AssignCloseImage(String closeIconFileName,
                                      String pressedCloseIconFileName)
        {
            NSImage closeImage = NSImage.FromStream
                                     (Assembly.GetExecutingAssembly().
                                     GetManifestResourceStream(
                                         closeIconFileName));

            CloseButton.Frame = new RectangleF(new PointF(0.0f, 0.0f),
                                               new SizeF(closeImage.Size.Height,
                                                         closeImage.Size.Width));
            NSImage pressedCloseImage = NSImage.FromStream
                                            (Assembly.GetExecutingAssembly().
                                            GetManifestResourceStream(
                                                pressedCloseIconFileName));

            CloseButton.Frame = new RectangleF(
                new PointF(0.0f, 0.0f),
                new SizeF(pressedCloseImage.Size.Height,
                          pressedCloseImage.Size.Width));

            CloseButton.Image             = closeImage;
            CloseButton.AlternateImage    = pressedCloseImage;
            CloseButton.Cell.HighlightsBy = (int)NSCellMask.ContentsCell;
        }
示例#5
0
        public WindowSidebar()
        {
            PInvokeUtils.RECT rc = new PInvokeUtils.RECT();

            var flags = SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_ALPHA |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_MAIN |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_ENABLE_DEBUG |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_TOOL;
            var wnd = this;

            wnd.CreateWindow(rc, flags);
            wnd.Title = Consts.AppName;

            var deleg = new WindowDelegate();

            wnd._nsview.Window.Delegate  = deleg;
            wnd._nsview.Window.Level     = NSWindowLevel.Floating;
            wnd._nsview.Window.StyleMask = wnd._nsview.Window.StyleMask & ~NSWindowStyle.Resizable;

            // Create status bar item
            _sItem       = NSStatusBar.SystemStatusBar.CreateStatusItem(26);
            _sItem.Image = NSImage.FromStream(File.OpenRead(NSBundle.MainBundle.ResourcePath + @"/drop.png"));
            //_sItem.AlternateImage = NSImage.FromStream(File.OpenRead(NSBundle.MainBundle.ResourcePath + @"/icon_menubarX2.png"));
            _sItem.Image.Template = true;
            _sItem.Action         = new ObjCRuntime.Selector("OnIconClick");
            _sItem.Target         = deleg;
        }
        protected void OnScreenshotReceive(object sender, ScreenshotReceivedEventArgs e)
        {
            if (e.Fullscreen)
            {
                //Bounds = e.Bounds;
            }

            //Ratio = (float)this.imageView.Bounds.Width / (float)Bounds.Width;

            /*if (this.imageView.InvokeRequired)
             * {
             *      SetDrawingAreaHeightCallback d = new SetDrawingAreaHeightCallback(setDrawingAreaHeight);
             *      this.Invoke(d, new object[] { (int)((float)Bounds.Height * Ratio) });
             * }
             * else
             * {
             *      setDrawingAreaHeight((int)((float)Bounds.Height * Ratio));
             * }*/

            if (e.Nothing)
            {
                return;
            }

            if (e.SystemId == this.SystemId)
            {
                using (var stream = new MemoryStream(e.Image))
                {
                    NSImage image = NSImage.FromStream(stream);

                    drawImage(image);
                }
            }
        }
        /// <summary>
        /// Gets the image from cache or converts the specified <paramref name="source"/> <see cref="OxyImage"/>.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns>The image.</returns>
        private NSImage GetImage(OxyImage source)
        {
            if (source == null)
            {
                return(null);
            }

            if (!this.imagesInUse.Contains(source))
            {
                this.imagesInUse.Add(source);
            }

            NSImage src;

            if (!this.imageCache.TryGetValue(source, out src))
            {
                using (var ms = new System.IO.MemoryStream(source.GetData()))
                {
                    src = NSImage.FromStream(ms);
                }

                if (src != null)
                {
                    this.imageCache.Add(source, src);
                }
            }

            return(src);
        }
示例#8
0
        internal static async Task <StorageItemThumbnail> CreatePhotoThumbnailAsync(StorageFile file)
        {
#if __MAC__
            NSImage image = NSImage.FromStream(await file.OpenStreamForReadAsync());
            double  ratio = image.Size.Width / image.Size.Height;

            NSImage newImage = new NSImage(new CGSize(240, 240 * ratio));
            newImage.LockFocus();
            image.Size = newImage.Size;

            image.Draw(new CGPoint(0, 0), new CGRect(0, 0, newImage.Size.Width, newImage.Size.Height), NSCompositingOperation.Copy, 1.0f);
            newImage.UnlockFocus();

            NSMutableData      buffer = new NSMutableData();
            CGImageDestination dest   = CGImageDestination.Create(buffer, UTType.JPEG, 1);
            dest.AddImage(newImage.CGImage);

            return(new StorageItemThumbnail(buffer.AsStream()));
#else
            UIImage image = UIImage.FromFile(file.Path);

            UIImage image2 = image.Scale(new CGSize(240, 240));
            image.Dispose();

            return(new StorageItemThumbnail(image2.AsJPEG().AsStream()));
#endif
        }
示例#9
0
        public static MacImageAdapter TryGet(Stream stream)
        {
            var img       = NSImage.FromStream(stream);
            var bitmapRep = img.Representations()[0] as NSBitmapImageRep;

            if (bitmapRep == null)
            {
                return(null);
            }

            var frames = GetValueForProperty(bitmapRep, NSImageFrameCount) as NSNumber;

            if (frames == null || frames.Int32Value <= 1)
            {
                return(null);
            }
            var images = new List <RImageFrame>();

            for (var i = 0; i < frames.Int32Value; i++)
            {
                SetValueForProperty(bitmapRep, NSBitmapImageRep.CurrentFrame, new NSNumber(i));
                var delay = GetValueForProperty(bitmapRep, NSBitmapImageRep.CurrentFrameDuration) as NSNumber;
                images.Add(new MacImageFrame(TimeSpan.FromSeconds(delay.DoubleValue)));
            }
            return(new MacImageAdapter(img, bitmapRep, images));
        }
示例#10
0
        public WindowSidebar()
        {
            var frm = NSScreen.MainScreen.VisibleFrame;

            PInvokeUtils.RECT rc = new PInvokeUtils.RECT()
            {
                right  = 670,
                bottom = (int)frm.Height - 50
            };

            var flags = SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_ALPHA |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_MAIN |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_ENABLE_DEBUG |
                        SciterXDef.SCITER_CREATE_WINDOW_FLAGS.SW_TOOL;
            var wnd = this;

            wnd.CreateWindow(rc, flags);
            wnd.Title = Consts.AppName;

            var deleg = new WindowDelegate();

            wnd._nsview.Window.Delegate = deleg;
            wnd._nsview.Window.Level    = NSWindowLevel.Floating;

            // Create status bar item
            _sItem                = NSStatusBar.SystemStatusBar.CreateStatusItem(25);
            _sItem.Image          = NSImage.FromStream(File.OpenRead(NSBundle.MainBundle.ResourcePath + @"/drop.png"));
            _sItem.Image.Template = true;
            _sItem.Action         = new ObjCRuntime.Selector("OnIconClick");
            _sItem.Target         = deleg;
            _sItem.HighlightMode  = true;
        }
 private void DisplayQRCode(byte[] bytes)
 {
     this.InvokeOnMainThread(() =>
     {
         using (var stream = new MemoryStream(bytes))
             this.ImageLoginCode.Image = NSImage.FromStream(stream);
     });
 }
示例#12
0
 public static NSImage ToNSImage(this Image image)
 {
     using (var stream = new System.IO.MemoryStream()) {
         image.Save(stream, ImageFormat.Png);
         stream.Position = 0;
         return(NSImage.FromStream(stream));
     }
 }
示例#13
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //блок инициализации полей
            NameField.StringValue   = item.Name;
            BrandField.StringValue  = item.Brand;
            PriceField.IntValue     = item.Price;
            AvailableField.IntValue = item.Available;
            Desc.Value      = item.Description;
            Imageview.Image = NSImage.FromStream(new MemoryStream(item.Image));

            //Кнопка отмены
            CancelButton.Activated += (sender, e) => DismissViewController(this);

            //Кнопка изменения с делегатом для обратного вызова в методе PrepareForsegue(адресата)
            EditedButton.Activated += (sender, e) =>
            {
                if (CheckExpressions())
                {
                    item.Name        = NameField.StringValue;
                    item.Brand       = BrandField.StringValue;
                    item.Price       = PriceField.IntValue;
                    item.Available   = AvailableField.IntValue;
                    item.Description = Desc.Value;

                    try
                    {
                        //Запрос к бд на изменение элемента
                        SqlClass.EditRow(item);

                        addOne(this, new EventArgs());
                        DismissViewController(this);
                    }
                    catch
                    {
                        (SqlClass.GetError("Не удалось добавить поле")).RunModal();
                    }
                }
                else
                {
                    (SqlClass.GetError("Поля введены не верно")).RunModal();
                }
            };

            UploadButton.Activated += (sender, e) =>
            {
                NSOpenPanel openpanel = new NSOpenPanel();
                openpanel.AllowedFileTypes = new string[] { @"jpg" };
                openpanel.RunModal();
                Imageview.Image = new NSImage(openpanel.Url);
                if (openpanel.Url.Path != null)
                {
                    item.Image = File.ReadAllBytes(openpanel.Url.Path);
                }
            };
        }
示例#14
0
 void stylizeGraph_OnDownloadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
     byte[] jpeg = _stylizeGraph.StylizeToJpeg("surfers.jpg", 0);
     using (System.IO.Stream s = new System.IO.MemoryStream(jpeg))
     {
         NSImage newImg = NSImage.FromStream(s);
         SetImage(newImg);
     }
 }
示例#15
0
 private void SetStatusItem()
 {
     if (_statusItem == null)
     {
         _statusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30);
     }
     _statusItem.Menu          = statusMenu;
     _statusItem.Image         = NSImage.FromStream(System.IO.File.OpenRead(NSBundle.MainBundle.ResourcePath + @"/icon.icns"));
     _statusItem.HighlightMode = true;
 }
        private async void UpdateIcon()
        {
            Stream icon = await this.viewModel.GetIconAsync();

            if (icon != null)
            {
                this.propertyIcon.Image = NSImage.FromStream(icon);
            }

            this.propertyIcon.Hidden = (icon == null);
        }
        async partial void FilePickerButtonClicked(Foundation.NSObject sender)
        {
            var pickedFile = await CrossFilePicker.Current.PickFile();

            FileNameLabel.StringValue = pickedFile.FileName;
            FilePathLabel.StringValue = pickedFile.FilePath;

            if (pickedFile.FileName.EndsWith("png") || pickedFile.FileName.EndsWith("jpg"))
            {
                FileImagePreview.Image = NSImage.FromStream(pickedFile.GetStream());
            }
        }
 void SetIcon(Icon icon)
 {
     using (var stream = icon.GetStream())
     {
         // Fun song and dance to avoid using the default 256/256 rep
         var icn = NSImage.FromStream(stream).BestRepresentation(new CGRect(0, 0, 32, 32), null, null);
         icn.Size = new CGSize(24, 24);
         var image = new NSImage(icn.Size);
         image.AddRepresentation(icn);
         image.Template = true;
         _item.Image    = image;
     }
 }
示例#19
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);
            }
        }
示例#20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OSXSurfaceSource"/> class from the specified stream.
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> that contains the surface data.</param>
        public OSXSurfaceSource(Stream stream)
        {
            Contract.Require(stream, "stream");

            var data = new Byte[stream.Length];

            stream.Read(data, 0, data.Length);

            using (var mstream = new MemoryStream(data))
            {
                this.image    = NSImage.FromStream(mstream);
                this.imageRep = new NSBitmapImageRep(image.CGImage);
            }
        }
示例#21
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Do any additional setup after loading the view.
            WallpaperService wallpaper = new WallpaperService();
            var model  = wallpaper.GetTodayWallpaperUrl();
            var stream = wallpaper.GetStream(model.Url);

            imgWallpaper.Image = NSImage.FromStream(stream);
            url = model.Url;
            lblInfo.StringValue        = model.Copyright;
            lblPictureDate.StringValue = model.Startdate;
        }
示例#22
0
        /// <inheritdoc/>
        public override Surface2D LoadIcon()
        {
            var bundle = NSBundle.MainBundle;

            if (bundle == null)
            {
                return(null);
            }

            var icon = default(NSImage);

            try
            {
                try
                {
                    if (String.Equals(Path.GetExtension(bundle.BundlePath), ".app", StringComparison.OrdinalIgnoreCase))
                    {
                        icon = NSWorkspace.SharedWorkspace.IconForFile(bundle.BundlePath);
                        if (icon == null)
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    else
                    {
                        using (var stream = typeof(UltravioletContext).Assembly.GetManifestResourceStream("TwistedLogik.Ultraviolet.uv.ico"))
                        {
                            icon = NSImage.FromStream(stream);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    return(null);
                }

                using (var source = new OSXSurfaceSource(icon))
                {
                    return(Surface2D.Create(source));
                }
            }
            finally
            {
                if (icon != null)
                {
                    icon.Dispose();
                }
            }
        }
        partial void CustomImage(NSObject sender)
        {
            var alert = new NSAlert {
                MessageText = "The cat that started it all!"
            };

            var asm = Assembly.GetExecutingAssembly();

            using (var stream = asm.GetManifestResourceStream("NSAlertSample.i-can-has-cheezburger.jpg")) {
                alert.Icon = NSImage.FromStream(stream);
            }

            alert.AddButton("No Can Has");

            Run(alert);
        }
示例#24
0
 public IImageWrapper GetImageResource(string resource)
 {
     try
     {
         var assembly  = System.Reflection.Assembly.GetAssembly(typeof(MacInspectorDelegate));
         var resources = assembly.GetManifestResourceNames();
         using (var stream = assembly.GetManifestResourceStream(resource))
         {
             return(new MacImageWrapper(NSImage.FromStream(stream)));
         }
     }
     catch (System.Exception ex)
     {
         return(null);
     }
 }
示例#25
0
        public override void FinishedLaunching(NSObject notification)
        {
            NSApplication.SharedApplication.ActivationPolicy = NSApplicationActivationPolicy.Accessory;

            // menu
            var menu = new NSMenu();

            // create status icon
            var icon = NSStatusBar.SystemStatusBar.CreateStatusItem(30);

            icon.Menu          = menu;
            icon.Image         = NSImage.FromStream(System.IO.File.OpenRead(NSBundle.MainBundle.ResourcePath + "/SwimmingPool.icns"));
            icon.HighlightMode = true;

            new MainMenu(menu);
        }
示例#26
0
        /// <summary>
        /// 插入图片到textView
        /// </summary>
        /// <param name="bytes">Stream.</param>
        private void AddImageToTextView(byte[] bytes, string originSizeUrl)
        {
            this.InvokeOnMainThread(() =>
            {
                using (var stream = new MemoryStream(bytes))
                {
                    ImageCell cell = new ImageCell(NSImage.FromStream(stream));
                    cell.SetData("picUrl", originSizeUrl);

                    NSTextAttachment am = new NSTextAttachment
                    {
                        AttachmentCell = cell
                    };
                    NSAttributedString nbs = NSAttributedString.FromAttachment(am);
                    this.TextPrint.TextStorage.Append(nbs);
                }
            });
        }
示例#27
0
        public async Task <NSImage> LoadImageAsync(ImageSource imagesource,
                                                   CancellationToken cancelationToken = default(CancellationToken), float scale = 1f)
        {
            NSImage image       = null;
            var     imageLoader = imagesource as UriImageSource;

            if (imageLoader != null && imageLoader.Uri != null)
            {
                using (var streamImage = await imageLoader.GetStreamAsync(cancelationToken).ConfigureAwait(false))
                {
                    if (streamImage != null)
                    {
                        image = NSImage.FromStream(streamImage);
                    }
                }
            }
            return(image);
        }
示例#28
0
        protected override void init(Stream stream, bool flip, Loader.LoadedCallbackMethod loadedCallback)
        {
            try
            {
                using (var image = NSImage.FromStream(stream))
                {
                    var rep    = image.Representations()[0];
                    int width  = rep.PixelsWide;
                    int height = rep.PixelsHigh;
                    Mipmaps = new Mipmap[1];
                    Size    = new Size2(width, height);

                    var data      = new byte[width * height * 4];
                    var emptyRect = RectangleF.Empty;
                    using (CGContext imageContext = new CGBitmapContext(data, width, height, 8, width * 4, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedLast))
                        using (var cgImage = image.AsCGImage(ref emptyRect, null, null))
                        {
                            imageContext.DrawImage(new RectangleF(0, 0, width, height), cgImage);

                            Mipmaps[0] = new Mipmap(data, width, height, 1, 4);
                            if (flip)
                            {
                                Mipmaps[0].FlipVertical();
                            }
                        }
                }
            }
            catch (Exception e)
            {
                FailedToLoad = true;
                Loader.AddLoadableException(e);
                if (loadedCallback != null)
                {
                    loadedCallback(this, false);
                }
                return;
            }

            Loaded = true;
            if (loadedCallback != null)
            {
                loadedCallback(this, true);
            }
        }
        private NSImage GetImage()
        {
            var src         = NSImage.FromStream(System.IO.File.OpenRead(filePath));
            var scaleFactor = BarHeight / src.Size.Height;

            var width      = (nint)(src.Size.Width * scaleFactor);
            var height     = (nint)(src.Size.Height * scaleFactor);
            var bpc        = 8;
            var stride     = 4 * width;
            var colorSpace = CGColorSpace.CreateDeviceRGB();
            var info       = CGImageAlphaInfo.PremultipliedLast;

            var context = new CGBitmapContext(null, width, height, bpc, stride, colorSpace, info);
            var rect    = new CGRect(0f, 0f, width, height);

            context.DrawImage(rect, src.CGImage);
            var ni = context.ToImage();

            return(new NSImage(ni, new CGSize(width, height)));
        }
示例#30
0
        public async Task <NSImage> LoadImageAsync(ImageSource imagesource,
                                                   CancellationToken cancelationToken = default(CancellationToken), float scale = 1f)
        {
            NSImage image        = null;
            var     streamsource = imagesource as StreamImageSource;

            if (streamsource?.Stream == null)
            {
                return(null);
            }
            using (
                var streamImage = await((IStreamImageSource)streamsource).GetStreamAsync(cancelationToken).ConfigureAwait(false))
            {
                if (streamImage != null)
                {
                    image = NSImage.FromStream(streamImage);
                }
            }
            return(image);
        }