Exemplo n.º 1
0
        /// <summary>
        /// This method is called prior to the removal of the UIViewthat is this
        /// UIViewController’s UIViewController.View from the display UIView hierarchy.
        /// </summary>
        /// <param name="animated">If set to <c>true</c> animated.</param>
        public override void ViewWillDisappear(bool animated)
        {
            base.ViewWillDisappear(animated);

            cancellationTokenSource?.Cancel();

            // dispose of unneeded assets
            InputImage.Dispose();
            imageView.Dispose();
            originalImageView.Dispose();
            blendedImage?.Dispose();
        }
        /// <summary>
        /// Set the photo for this cell
        /// </summary>
        public void SetPhoto(Photo photo)
        {
            //Free up the previous image if there was one
            if (image != null)
            {
                image.Dispose();
            }

            date.Text        = photo.Date.ToShortTimeString() + " " + photo.Date.ToShortDateString();
            description.Text = photo.Description;
            this.photo.Image =
                image        = photo.Image.ToUIImage();
        }
Exemplo n.º 3
0
        // http://stackoverflow.com/questions/8754124/uiimageview-uiimage-memory-tag-70-release-timing-when-scrolling
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_galleryImageView != null)
                {
                    UIImage image = _galleryImageView.Image;
                    _galleryImageView.Image = null;
                    image.Dispose();
                    _galleryImageView.RemoveFromSuperview();
                    _galleryImageView.Dispose();
                    _galleryImageView = null;
                }

                if (_pdvc != null)
                {
                    if (_pdvc.View != null && _pdvc.View.Superview != null)
                    {
                        _pdvc.View.RemoveFromSuperview();
                    }
                    _pdvc.Dispose();
                    _pdvc = null;
                }
            }
            base.Dispose(disposing);
        }
Exemplo n.º 4
0
        private void CreateTcpClient()
        {
            if (this.tcpClient != null)
            {
                this.tcpClient.Disconnect();
            }

            this.tcpClient = new AsyncTcpClient();
            this.tcpClient.DataReceived += (sender, args) =>
            {
                var bitmapContainer = JsonConvert.DeserializeObject <BitmapContainer>(args.Value);

                var image = bitmapContainer.EncodedBitmap.ToUIImage();
                if (image != null)
                {
                    UIImage oldImage = null;
                    this.InvokeOnMainThread(() =>
                    {
                        oldImage = imgScreenshot.Image;

                        imgScreenshot.Image = image;
                    });

                    if (oldImage != null)
                    {
                        oldImage.Dispose();
                    }
                }
            };
        }
        /// <summary>
        /// Resize image maintain aspect ratio
        /// </summary>
        /// <param name="imageSource"></param>
        /// <param name="scale"></param>
        /// <returns></returns>
        public static UIImage ResizeImageWithAspectRatio(this UIImage imageSource, float scale)
        {
            if (scale > 1.0f)
            {
                return(imageSource);
            }


            using (var c = CIContext.Create())
            {
                var sourceImage = CIImage.FromCGImage(imageSource.CGImage);
                var orientation = imageSource.Orientation;
                imageSource?.Dispose();

                var transform = new CILanczosScaleTransform
                {
                    Scale       = scale,
                    Image       = sourceImage,
                    AspectRatio = 1.0f
                };

                var output = transform.OutputImage;
                using (var cgi = c.CreateCGImage(output, output.Extent))
                {
                    transform?.Dispose();
                    output?.Dispose();
                    sourceImage?.Dispose();

                    return(UIImage.FromImage(cgi, 1.0f, orientation));
                }
            }
        }
Exemplo n.º 6
0
        public Task <byte[]> SelectFromLibrary()
        {
            var tcs = new TaskCompletionSource <byte[]>();

            TweetStation.Camera.SelectPicture(this, (obj) =>
            {
                UIImage originalImage = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
                if (originalImage != null)
                {
                    // do something with the image
                    Console.WriteLine("got the original image");

                    //TODO : take care of the image size

                    var jpegData = originalImage.AsJPEG(0.5f);

                    originalImage.Dispose();
                    originalImage = null;

                    var buffer = jpegData.ToArray();
                    jpegData.Dispose();
                    jpegData = null;

                    tcs.TrySetResult(buffer);
                }
            });

            return(tcs.Task);
        }
Exemplo n.º 7
0
        private Task <byte[]> GetImageAsByte(bool usePNG, int quality, int desiredWidth, int desiredHeight)
        {
            return(Task.Run(() => {
                if (Control == null || Control.Image == null)
                {
                    return null;
                }

                UIImage image = Control.Image;

                if (desiredWidth != 0 || desiredHeight != 0)
                {
                    image = image.ResizeUIImage((double)desiredWidth, (double)desiredHeight, InterpolationMode.Default);
                }

                NSData imageData = usePNG ? image.AsPNG() : image.AsJPEG((nfloat)quality / 100f);

                if (imageData == null || imageData.Length == 0)
                {
                    return null;
                }

                var encoded = imageData.ToArray();
                imageData.Dispose();

                if (desiredWidth != 0 || desiredHeight != 0)
                {
                    image.Dispose();
                }

                return encoded;
            }));
        }
Exemplo n.º 8
0
        public override void DidCropToImage(TOCropViewController cropViewController, UIImage image, CoreGraphics.CGRect cropRect, nint angle)
        {
            IsCropped = true;

            try
            {
                if (image != null)
                {
                    _page.CroppedImage = image.AsJPEG().ToArray();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }

                CloseView();
            }
        }
Exemplo n.º 9
0
 private void ReadTask()
 {
     results = barcodeReader.DecodeImage(uiImage, "", out error);
     if (results != null && results.Length > 0)
     {
         for (int i = 0; i < results.Length; i++)
         {
             if (i == 0)
             {
                 result = "Code[1]: " + results[0].BarcodeText;
             }
             else
             {
                 result = result + "\n\n" + "Code[" + (i + 1) + "]: " + results[i].BarcodeText;
             }
         }
         //Console.WriteLine(results[0].BarcodeText);
     }
     else
     {
         result = "";
     }
     DispatchQueue.MainQueue.DispatchAsync(update);
     context.Dispose();
     cgImage.Dispose();
     uiImage.Dispose();
     ready = true;
 }
Exemplo n.º 10
0
        public UIButton CreateBackButton(int leftCapWidth)
        {
            backButtonCapWidth = leftCapWidth;
            UIImage buttonImage          = UIImage.FromBundle("Images/gallery/backButton.png").StretchableImage(backButtonCapWidth, 0);
            UIImage buttonHighlightImage = UIImage.FromBundle("Images/gallery/backButtonHighlighted.png").StretchableImage(backButtonCapWidth, 0);

            UIButton button = UIButton.FromType(UIButtonType.Custom);

            button.TitleLabel.Font          = UIFont.BoldSystemFontOfSize(UIFont.SmallSystemFontSize);
            button.TitleLabel.TextColor     = UIColor.White;
            button.TitleLabel.ShadowOffset  = new SizeF(0, -1);
            button.TitleLabel.ShadowColor   = UIColor.DarkGray;
            button.TitleLabel.LineBreakMode = UILineBreakMode.TailTruncation;
            button.TitleEdgeInsets          = new UIEdgeInsets(0, 6.0f, 0, 3.0f);
            button.Frame = new RectangleF(0, 0, 0, buttonImage.Size.Height);

            SetBackButtonText(button);

            // Set the stretchable images as the background for the button
            button.SetBackgroundImage(buttonImage, UIControlState.Normal);
            button.SetBackgroundImage(buttonHighlightImage, UIControlState.Highlighted);
            button.SetBackgroundImage(buttonHighlightImage, UIControlState.Selected);
            button.AddTarget(delegate { _navigationController.PopViewControllerAnimated(true); }, UIControlEvent.TouchUpInside);

            buttonImage.Dispose();
            buttonHighlightImage.Dispose();

            return(button);
        }
        protected virtual async Task <UIImage> GetImage(ImageSource imageSource)
        {
            if (imageSource == null)
            {
                return(null);
            }

            UIImage image = null;

            try
            {
                var handler = new FileImageSourceHandler();
                image = await handler.LoadImageAsync(imageSource);
            }
            catch
            {
                // ignored
            }


            if (Element == null)
            {
                image?.Dispose();
                return(null);
            }

            return(image);
        }
Exemplo n.º 12
0
        private void AddTabBarArrow(int index)
        {
            if (this._tabBarArrow != null)
            {
                _tabBarArrow.RemoveFromSuperview();
                _tabBarArrow.Dispose();
            }

            UIImage tabBarArrowImage = UIImage.FromBundle("Images/tabArrow.png");

            this._tabBarArrow = new UIImageView(tabBarArrowImage);

            // To get the vertical location we start at the bottom of the window, go up by height of the tab bar,
            // go up again by the height of arrow and then come back down 2 pixels so the arrow is slightly on top
            // of the tab bar.

            var verticalLocation =
                (Util.IsLandscape() ? AppDelegate.ApplicationWindow.Frame.Size.Width : AppDelegate.ApplicationWindow.Frame.Size.Height) -
                this.TabBar.Frame.Size.Height -
                tabBarArrowImage.Size.Height + 2;

            _tabBarArrow.Frame = new RectangleF(
                this.HorizontalLocationFor(index),
                verticalLocation,
                tabBarArrowImage.Size.Width,
                tabBarArrowImage.Size.Height
                );

            this.View.AddSubview(_tabBarArrow);
            tabBarArrowImage.Dispose();
        }
Exemplo n.º 13
0
        public async Task <byte[]> FixImagePerspective(string filename)
        {
            byte[] imageBytes = null;

            DocScanner ocv = new DocScanner();

            UIImage image = UIImage.FromBundle(filename);

            NSObject[] result = ocv.DetectBorders(image);
            if (result != null)
            {
                UIImage fixedImage = ocv.FixPerspective();
                if (fixedImage != null)
                {
                    using (NSData imageData = fixedImage.AsJPEG())
                    {
                        imageBytes = new byte[imageData.Length];
                        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, imageBytes, 0, Convert.ToInt32(imageData.Length));
                    }
                    image.Dispose();
                    fixedImage.Dispose();
                }
            }

            return(imageBytes);
        }
Exemplo n.º 14
0
        /*
         * Called if a full result is found. A full result is considered to be a successful preview, folloewd by a successful full scan.
         */
        void IAnylineDocumentModuleDelegate.HasResult(AnylineDocumentModuleView anylineDocumentModuleView, UIImage transformedImage, UIImage fullFrame, ALSquare corners)
        {
            if (_disposing)
            {
                return;
            }

            if (_scanView == null)
            {
                return;
            }

            //we'll go to a temporary new view controller, so we keep this one alive
            _keepScanViewControllerAlive = true;

            _resultImage = transformedImage;

            using (var vc = new UIViewController())
            {
                var iv = new UIImageView(_scanView.Frame)
                {
                    Image       = _resultImage,
                    ContentMode = UIViewContentMode.ScaleAspectFit
                };
                vc.View.AddSubview(iv);

                NavigationController?.PushViewController(vc, true);
            }

            fullFrame?.Dispose();
            transformedImage?.Dispose();
        }
Exemplo n.º 15
0
        /// <summary>
        /// Shows the photo.
        /// </summary>
        /// <param name="resizedImage">Resized image.</param>
        public async void ShowPhoto(UIImage resizedImage)
        {
            try
            {
                Debug.WriteLine("show photo - line 171");
                if (resizedImage != null)
                {
                    image.Image = resizedImage;
                    if (resizedImage != null)
                    {
                        resizedImage.Dispose();
                        resizedImage = null;
                    }
                    pictureTaken(image);
                }
                this.DismissViewControllerAsync(false);

                //FreemediaController();
                GC.SuppressFinalize(this);
                GC.Collect();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception Occured in Showphoto method due to " + ex.Message);
            }
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _ArrowImage.Dispose();

                if (_Activity != null)
                {
                    _Activity.Dispose();
                    _Activity = null;
                }

                if (_LastUpdateLabel != null)
                {
                    _LastUpdateLabel.Dispose();
                    _LastUpdateLabel = null;
                }

                if (_StatusLabel != null)
                {
                    _StatusLabel.Dispose();
                    _StatusLabel = null;
                }

                if (_ArrowView != null)
                {
                    _ArrowView.Dispose();
                    _ArrowView = null;
                }
            }

            base.Dispose(disposing);
        }
Exemplo n.º 17
0
        public void Dispose()
        {
            if (cgdata != null)
            {
                cgdata.Dispose();
                cgdata = null;
            }

            if (cgimage != null)
            {
                cgimage.Dispose();
                cgimage = null;
            }

            if (image != null)
            {
                image.Dispose();
                image = null;
            }

            if (colorSpace != null)
            {
                colorSpace.Dispose();
                colorSpace = null;
            }

            //if (bits != IntPtr.Zero)
            //	Marshal.FreeHGlobal (bits);

            bits = null;
        }
Exemplo n.º 18
0
        public ExtendedDisplayViewController() : base("ExtendedDisplayViewController", null)
        {
            this.tcpClient = new AsyncTcpClient();
            this.tcpClient.DataReceived += (sender, args) =>
            {
                var bitmapContainer = JsonConvert.DeserializeObject <BitmapContainer>(args.Value);

                var image = bitmapContainer.EncodedBitmap.ToUIImage();
                if (image != null)
                {
                    UIImage oldImage = null;
                    this.InvokeOnMainThread(() =>
                    {
                        oldImage = imgDisplay.Image;

                        imgDisplay.Image = image;
                    });

                    if (oldImage != null)
                    {
                        oldImage.Dispose();
                    }
                }
            };
        }
Exemplo n.º 19
0
        /*
         * This method is called when a result has been found. We'll show the transformed image on a new viewController.
         */
        void IAnylineDocumentModuleDelegate.HasResult(AnylineDocumentModuleView anylineDocumentModuleView, UIImage transformedImage, UIImage fullFrame)
        {
            //we'll go to a temporary new view controller, so we keep this one alive
            keepScanViewControllerAlive = true;

            this.resultImage = transformedImage;

            using (UIViewController vc = new UIViewController())
            {
                UIImageView iv = new UIImageView(scanView.Frame);
                iv.Image       = resultImage;
                iv.ContentMode = UIViewContentMode.ScaleAspectFit;
                vc.View.AddSubview(iv);

                this.NavigationController.PushViewController(vc, true);
            }

            if (fullFrame != null)
            {
                fullFrame.Dispose();
            }
            if (transformedImage != null)
            {
                transformedImage.Dispose();
            }

            fullFrame        = null;
            transformedImage = null;
        }
        public override void DidCropToImage(TOCropViewController cropViewController, UIImage image, CoreGraphics.CGRect cropRect, nint angle)
        {
            DidCrop = true;

            try
            {
                if (image != null)
                {
                    App.CroppedImage = image.AsPNG().ToArray();
                }
            }
            catch (Exception ex) {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }
            }

            parent.DismissViewController(true, App.PopModal);
        }
Exemplo n.º 21
0
        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            //don't clean up objects, if we want the controller to be kept alive
            if (keepScanViewControllerAlive)
            {
                return;
            }

            //remove notification view
            if (notificationView != null)
            {
                notificationView.RemoveFromSuperview();
                notificationView.Dispose();
                notificationView = null;
            }
            //remove image
            if (resultImage != null)
            {
                resultImage.Dispose();
                resultImage = null;
            }
            //we have to erase the scan view so that there are no dependencies for the viewcontroller left.
            scanView.RemoveFromSuperview();
            scanView.Dispose();
            scanView = null;

            base.Dispose();
        }
Exemplo n.º 22
0
        protected override void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _applicationContext = null;
                }

                if (_backgroundImageCache != null)
                {
                    _backgroundImageCache.Dispose();
                }
                _backgroundImageCache = null;

                if (_view != null)
                {
                    _view.TouchUpInside -= Button_Click;
                }

                _disposed = true;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 23
0
        public override void DidCropToImage(TOCropViewController cropViewController, UIImage image, CoreGraphics.CGRect cropRect, nint angle)
        {
            DidCrop = true;

            try
            {
                if (image != null)
                {
                    CroppedImage = image.AsPNG().ToArray();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }
            }

            parent.DismissViewController(true, () => { Xamarin.Forms.Application.Current.MainPage.Navigation.PopModalAsync(); });
        }
Exemplo n.º 24
0
        public override void Draw(RectangleF rect)
        {
            if (_overlayImageView != null)
            {
                //Util.Log ("Drawing blended image with overlay alpha " + _overlayImageView.Alpha);
                UIImage     bottomImage = _underlayImageView.Image;
                UIImage     topImage    = _overlayImageView.Image;
                UIImageView imageView   = new UIImageView(bottomImage);
                UIImageView subView     = new UIImageView(topImage);
                bottomImage.Dispose();
                topImage.Dispose();

                subView.Alpha = _overlayImageView.Alpha;
                imageView.AddSubview(subView);

                UIGraphics.BeginImageContext(imageView.Frame.Size);
                imageView.Layer.RenderInContext(UIGraphics.GetCurrentContext());
                UIImage blendedImage = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                subView.Dispose();
                imageView.Dispose();

                blendedImage.Draw(rect);
                blendedImage.Dispose();
            }
            else
            {
                // Draw nothing
            }
        }
Exemplo n.º 25
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
        }
        protected override void Dispose(bool disposing)
        {
            bigFlowerImageView.Dispose();
            bigFlowerImageView = null;

            carlImageView.Dispose();
            carlImageView = null;

            jaguarPrintImageH.Dispose();
            jaguarPrintImageH = null;

            jaguarPrintImageV.Dispose();
            jaguarPrintImageV = null;

            topJaguarPrintImageView.Dispose();
            topJaguarPrintImageView = null;

            bottomJaguarPrintImageView.Dispose();
            bottomJaguarPrintImageView = null;

            leftJaguarPrintImageView.Dispose();
            leftJaguarPrintImageView = null;

            rightJaguarPrintImageView.Dispose();
            rightJaguarPrintImageView = null;

            dimmingView.Dispose();
            dimmingView = null;

            base.Dispose(disposing);
        }
Exemplo n.º 27
0
        internal static async Task <StorageItemThumbnail> CreateVideoThumbnailAsync(StorageFile file)
        {
            AVAsset asset = AVUrlAsset.FromUrl(NSUrl.FromFilename(file.Path));
            AVAssetImageGenerator generator = AVAssetImageGenerator.FromAsset(asset);

            generator.AppliesPreferredTrackTransform = true;
            NSError error;
            CMTime  actualTime;
            CMTime  time  = CMTime.FromSeconds(asset.Duration.Seconds / 2, asset.Duration.TimeScale);
            CGImage image = generator.CopyCGImageAtTime(time, out actualTime, out error);

#if __MAC__
            NSMutableData      buffer = new NSMutableData();
            CGImageDestination dest   = CGImageDestination.Create(buffer, UTType.JPEG, 1, null);
            dest.AddImage(image);
            return(new StorageItemThumbnail(buffer.AsStream()));
#else
            UIImage image2 = UIImage.FromImage(image);
            image.Dispose();

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

            return(new StorageItemThumbnail(image3.AsJPEG().AsStream()));
#endif
        }
Exemplo n.º 28
0
        public static byte[] ToNSData(this UIImage image)
        {
            if (image == null)
            {
                return(null);
            }
            NSData data = null;

            try
            {
                data = image.AsPNG();
                return(data.ToArray());
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }
                if (data != null)
                {
                    data.Dispose();
                    data = null;
                }
            }
        }
Exemplo n.º 29
0
        public static UIColor CreateRepeatingBackground()
        {
            UIImage bgImage = LoadSplashImage();

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

            var size = new CoreGraphics.CGSize(40f, bgImage.Size.Height);

            UIGraphics.BeginImageContext(size);
            var ctx = UIGraphics.GetCurrentContext();

            ctx.TranslateCTM(0, bgImage.Size.Height);
            ctx.ScaleCTM(1f, -1f);

            ctx.DrawImage(new CoreGraphics.CGRect(-10, 0, bgImage.Size.Width, bgImage.Size.Height), bgImage.CGImage);
            ctx.ClipToRect(new CoreGraphics.CGRect(0, 0, size.Width, size.Height));

            var img = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();
            bgImage.Dispose();

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

            var ret = UIColor.FromPatternImage(img);

            img.Dispose();
            return(ret);
        }
Exemplo n.º 30
0
        public Stream ResizeImage(
            Stream imageStream,
            double width,
            double height,
            string format = "jpeg",
            int quality   = 96)
        {
            if (imageStream == null)
            {
                return(null);
            }

            UIImage image = null;

            try {
                using (var memoryStream = new MemoryStream()) {
                    imageStream.CopyTo(memoryStream);
                    var data = memoryStream.ToArray();
                    image = UIImage.LoadFromData(NSData.FromArray(data));
                }
            } catch (Exception e) {
                Console.WriteLine($"ResizeImage: {e.Message}");
                return(null);
            }

            // No need to resize if required size is greater than original
            var scale = Math.Min(width / image.Size.Width,
                                 height / image.Size.Height);

            if (scale > 1.0)
            {
                return(imageStream);
            }

            width  = (float)(scale * image.Size.Width);
            height = (float)(scale * image.Size.Height);

            UIGraphics.BeginImageContextWithOptions(
                new CGSize(width, height),
                opaque: true,
                scale: 0);
            image.Draw(new CGRect(0, 0, width, height));
            var resized = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            var stream = new MemoryStream();

            var resizeData = ((format == "png") ?
                              resized.AsPNG().ToArray() :
                              resized.AsJPEG((nfloat)(0.01 * quality)).ToArray());

            image.Dispose();
            resized.Dispose();

            stream.Write(resizeData, 0, resizeData.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return(stream);
        }
Exemplo n.º 31
0
		public static UIImage CopyAndDispose(UIImage original)
		{
			UIGraphics.BeginImageContextWithOptions(original.Size, false, 0);
			original.Draw(new RectangleF(0, 0, original.Size.Width, original.Size.Height));
			UIImage copy = UIGraphics.GetImageFromCurrentImageContext();
		  	UIGraphics.EndImageContext();	
		    original.Dispose();
			return copy;
		}
Exemplo n.º 32
0
 public static void ImageToByteArray(UIImage image, out byte[] mediaByteArray)
 {
     using (NSData imgData = image.AsJPEG ())
     {
         mediaByteArray = new byte[imgData.Length];
         System.Runtime.InteropServices.Marshal.Copy (imgData.Bytes, mediaByteArray, 0, Convert.ToInt32 (imgData.Length));
     }
     image.Dispose ();
 }
		void MediaChooser (object sender, UIButtonEventArgs e)
		{
			if (e.ButtonIndex == 1)
			{
			
				System.Console.WriteLine ("Camera");

				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android
				if (!picker.IsCameraAvailable)
				{
					Console.WriteLine("No camera!");				
				}
				else 
				{
					picker.TakePhotoAsync 
						(
						  new StoreCameraMediaOptions 
							{
							  Name = "test.jpg"
							, Directory = "MediaPickerSample"
							}
						).ContinueWith 
							(
								t =>
								{
									if (t.IsCanceled) 
									{
									Console.WriteLine ("User canceled");
									return;
								}
								Console.WriteLine (t.Result.Path);
								imageView.Image = new UIImage(t.Result.Path);
								}
							, TaskScheduler.FromCurrentSynchronizationContext()
							);
				}

				image_bytes  = UIImageViewToByteArray(imageView.Image);

				image.Dispose ();

			} 
			else if (e.ButtonIndex == 2) 
			{
			
				System.Console.WriteLine ("Library");

				var picker = new MediaPicker ();
				//           new MediaPicker (this); on Android
			
				picker.PickPhotoAsync()
					.ContinueWith (t => {
						if (t.IsCanceled) {
							Console.WriteLine ("User canceled");
							return;
						}
						Console.WriteLine (t.Result.Path);
						imageView.Image = new UIImage(t.Result.Path);
					}, TaskScheduler.FromCurrentSynchronizationContext());
				}

			//MOKEEEEEEEEE UIImage To ByteArray
			image = imageView.Image;

			image_bytes = UIImageViewToByteArray(image);

			image.Dispose ();
		}
Exemplo n.º 34
0
 static void OnPhotoSaved(UIImage photo, NSError error)
 {
     // dispose of the full-size photograph
     photo.Dispose ();
 }
Exemplo n.º 35
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);
            Otazky = db.Get();
            SetRandom();

            SetRootSections();

            var o = new Olenenok(root);

            viewController = o;

            window.RootViewController = viewController;

            viewController.OrientationChanged += (object sender, EventArgs e) => {
                if(Current.Url != "placeholder") {

                float _scale =
                    (UIDevice.CurrentDevice.Orientation.ToString() == UIInterfaceOrientation.LandscapeLeft.ToString() ||
                     UIDevice.CurrentDevice.Orientation.ToString() == UIInterfaceOrientation.LandscapeRight.ToString()) ? 1.04f : 1.6f;

                var _i = UIImage.FromBundle("Images/"+ Current.Url);
                var _i2 = new UIImage(_i.CGImage, _scale, UIImageOrientation.Up);

                var _img = new UIImageView(_i2);

                picSection.Clear();
                picSection.Add(_img);

                _i.Dispose(); _i2.Dispose();

                //picSection.Reload(picSection, UITableViewRowAnimation.Fade);
                root.Reload(picSection, UITableViewRowAnimation.Fade);
                }

            };

            GestureFuch();

            window.MakeKeyAndVisible ();

            return true;
        }
Exemplo n.º 36
0
        private static UIImage ScaleImage(UIImage image, int maxSize)
        {
            UIImage res = image;

            CGImage imageRef = image.CGImage;

            CGImageAlphaInfo alphaInfo = imageRef.AlphaInfo;
            CGColorSpace colorSpaceInfo = CGColorSpace.CreateDeviceRGB();
            if (alphaInfo == CGImageAlphaInfo.None)
            {
                alphaInfo = CGImageAlphaInfo.NoneSkipLast;
            }

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

            if (maxSize > 0 && maxSize < Math.Max(width, height))
            {
                try
                {
                    if (height >= width)
                    {
                        width = (int) Math.Floor(width*(maxSize/(double) height));
                        height = maxSize;
                    }
                    else
                    {
                        height = (int) Math.Floor(height*(maxSize/(double) width));
                        width = maxSize;
                    }

                    int bytesPerRow = (int) image.Size.Width*4;
                    var buffer = new byte[(int) (bytesPerRow*image.Size.Height)];

                    CGBitmapContext bitmap;
                    if (image.Orientation == UIImageOrientation.Up || image.Orientation == UIImageOrientation.Down)
                        bitmap = new CGBitmapContext(buffer, width, height, imageRef.BitsPerComponent,
                            imageRef.BytesPerRow, colorSpaceInfo, alphaInfo);
                    else
                        bitmap = new CGBitmapContext(buffer, height, width, imageRef.BitsPerComponent,
                            imageRef.BytesPerRow, colorSpaceInfo, alphaInfo);

                    switch (image.Orientation)
                    {
                        case UIImageOrientation.Left:
                            bitmap.RotateCTM((float) Math.PI/2);
                            bitmap.TranslateCTM(0, -height);
                            break;
                        case UIImageOrientation.Right:
                            bitmap.RotateCTM(-((float) Math.PI/2));
                            bitmap.TranslateCTM(-width, 0);
                            break;
                        case UIImageOrientation.Up:
                            break;
                        case UIImageOrientation.Down:
                            bitmap.TranslateCTM(width, height);
                            bitmap.RotateCTM(-(float) Math.PI);
                            break;
                    }

                    bitmap.DrawImage(new RectangleF(0, 0, width, height), imageRef);
                    res = UIImage.FromImage(bitmap.ToImage());
                }
                finally
                {
                    image.Dispose();
                }
            }


            return res;
        }
Exemplo n.º 37
0
        void OnPhotoChosen(UIImagePickerController picker, UIImage photo)
        {
            Photograph = PhotoManager.ScaleToSize (photo, (int) PhotoWidth, (int) PhotoHeight);

            if (picker.SourceType == UIImagePickerControllerSourceType.Camera)
                photo.SaveToPhotosAlbum (OnPhotoSaved);
            else
                photo.Dispose ();

            popover.Dismiss (true);
        }
Exemplo n.º 38
0
        static void SetRootSections()
        {
            if(root == null) {
                root = new RootElement(null);
                sections = new List<Section>();
            }

            else {
                sections.ForEach(s =>
                                 root.Remove(s, UITableViewRowAnimation.Fade));
                sections = new List<Section>();

            }

            var queSection = new Section() { MakeElement(Current.Question, true) };

            var answers = new Section();

            picSection = new Section();
            if(Current.Url != "placeholder") {

                float scale =
                    (UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft ||
                     UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.LandscapeRight) ? 1.04f : 1.6f;

                var i = UIImage.FromBundle("Images/"+ Current.Url);
                var i2 = new UIImage(i.CGImage, scale, UIImageOrientation.Up);

                var img = new UIImageView(i2);

                i.Dispose();
                i2.Dispose();

                picSection.Add(img);

                root.Add(picSection);
                sections.Add(picSection);

            }

            root.Add(queSection);
            sections.Add(queSection);

            var a1 = MakeElement(Current.Answer1);
            var a2 = MakeElement(Current.Answer2);
            var a3 = MakeElement(Current.Answer3);

            answers.Add(a1);
            answers.Add(a2);

            if(Current.Answer3 != null) {
                answers.Add(a3);
            }

            root.Add(answers);
            sections.Add(answers);

            NSAction action = () => {
                if(Current.Right == 1) {
                    a1.Accessory = UITableViewCellAccessory.Checkmark;
                    a1.GetImmediateRootElement().Reload(answers, UITableViewRowAnimation.Fade);
                }
                if(Current.Right == 2) {
                    a2.Accessory = UITableViewCellAccessory.Checkmark;
                    a2.GetImmediateRootElement().Reload(answers, UITableViewRowAnimation.Fade);
                }
                if(Current.Right == 3) {
                    a3.Accessory = UITableViewCellAccessory.Checkmark;
                    a3.GetImmediateRootElement().Reload(answers, UITableViewRowAnimation.Fade);
                }
            };

            a1.Tapped += action;
            a2.Tapped += action;
            a3.Tapped += action;
        }