public async void SavePictureToDisk(string photoPath) { var someImage = new UIImage(photoPath); someImage.SaveToPhotosAlbum((image, error) => { var o = image; }); }
public async Task <bool> SaveImage(string directory, string filename, ImageSource img) { bool success = false; NSData imgData = null; var renderer = new Xamarin.Forms.Platform.iOS.StreamImagesourceHandler(); UIKit.UIImage photo = await renderer.LoadImageAsync(img); var savedImageFilename = System.IO.Path.Combine(directory, filename); NSFileManager.DefaultManager.CreateDirectory(directory, true, null); if (System.IO.Path.GetExtension(filename).ToLower() == ".png") { imgData = photo.AsPNG(); } else { imgData = photo.AsJPEG(100); } NSError err = null; success = imgData.Save(savedImageFilename, NSDataWritingOptions.Atomic, out err); return(success); }
private UIColor GetPixelColor(CGPoint point, UIImage image) { var rawData = new byte[4]; var handle = GCHandle.Alloc(rawData); UIColor resultColor = null; try { using (var colorSpace = CGColorSpace.CreateDeviceRGB()) { using (var context = new CGBitmapContext(rawData, 1, 1, 8, 4, colorSpace, CGImageAlphaInfo.PremultipliedLast)) { context.DrawImage(new CGRect(-point.X, point.Y - image.Size.Height, image.Size.Width, image.Size.Height), image.CGImage); float red = (rawData[0]) / 255.0f; float green = (rawData[1]) / 255.0f; float blue = (rawData[2]) / 255.0f; float alpha = (rawData[3]) / 255.0f; resultColor = UIColor.FromRGBA(red, green, blue, alpha); } } } finally { handle.Free(); } return resultColor; }
public RaffleDetailScreenController(Tap5050Event raffle,UIImage raffleImage) { //objects this.raffle = raffle; this.raffleImage = raffleImage; this.selectedGoalView = SelectedGoalView.Detail; }
public ImageLoaderStringElement (string caption, NSAction tapped, NSUrl imageUrl, UIImage placeholder) : base (caption, tapped) #endif { Placeholder = placeholder; ImageUrl = imageUrl; this.Accessory = UITableViewCellAccessory.None; }
public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Color Controls"; View.BackgroundColor = UIColor.White; resetButton = UIButton.FromType (UIButtonType.RoundedRect); resetButton.Frame = new CGRect(110, 60, 90, 40); resetButton.SetTitle ("Reset", UIControlState.Normal); resetButton.TouchUpInside += (sender, e) => { sliderSaturation.Value = 1; sliderBrightness.Value = 0; sliderContrast.Value = 1; HandleValueChanged (sender, e); }; View.Add (resetButton); labelC = new UILabel(new CGRect(10, 110, 90, 20)); labelS = new UILabel(new CGRect(10, 160, 90, 20)); labelB = new UILabel(new CGRect(10, 210, 90, 20)); labelC.Text = "Contrast"; labelS.Text = "Saturation"; labelB.Text = "Brightness"; View.Add (labelC); View.Add (labelS); View.Add (labelB); sliderBrightness = new UISlider(new CGRect(100, 110, 210, 20)); sliderSaturation = new UISlider(new CGRect(100, 160, 210, 20)); sliderContrast = new UISlider(new CGRect(100, 210, 210, 20)); // http://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CoreImageFilterReference/Reference/reference.html#//apple_ref/doc/filter/ci/CIColorControls // set min/max values on slider to match CIColorControls filter sliderSaturation.MinValue = 0; sliderSaturation.MaxValue = 2; sliderBrightness.MinValue = -1; sliderBrightness.MaxValue = 1; sliderContrast.MinValue = 0; sliderContrast.MaxValue = 4; // set default values sliderSaturation.Value = 1; sliderBrightness.Value = 0; sliderContrast.Value = 1; sliderContrast.TouchUpInside += HandleValueChanged; sliderSaturation.TouchUpInside += HandleValueChanged; sliderBrightness.TouchUpInside += HandleValueChanged; View.Add (sliderContrast); View.Add (sliderSaturation); View.Add (sliderBrightness); imageView = new UIImageView(new CGRect(10, 240, 300, 200)); sourceImage = UIImage.FromFile ("clouds.jpg"); imageView.Image = sourceImage; View.Add (imageView); }
public void Set(Uri imgUrl, string time, UIImage actionImage, NSMutableAttributedString header, NSMutableAttributedString body, List<Link> headerLinks, List<Link> bodyLinks, Action<NSUrl> webLinkClicked, bool multilined) { if (imgUrl == null) Image.Image = Images.Avatar; else Image.SetImage(new NSUrl(imgUrl.AbsoluteUri), Images.Avatar); Time.Text = time; ActionImage.Image = actionImage; if (header == null) header = new NSMutableAttributedString(); if (body == null) body = new NSMutableAttributedString(); Header.AttributedText = header; Header.Delegate = new LabelDelegate(headerLinks, webLinkClicked); Body.AttributedText = body; Body.Hidden = body.Length == 0; Body.Lines = multilined ? 0 : 4; Body.Delegate = new LabelDelegate(bodyLinks, webLinkClicked); foreach (var b in headerLinks) Header.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range); foreach (var b in bodyLinks) Body.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range); AdjustableConstraint.Constant = Body.Hidden ? 0f : 6f; }
public ImageViewController (UIImage image) { ImageView = new ZoomImageView { Image = image, AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight }; }
public ButtonElement (string caption, string value, UIImage image = null) : base (caption, value, UITableViewCellStyle.Value1) { Image = image; Accessory = UITableViewCellAccessory.DisclosureIndicator; SelectionStyle = UITableViewCellSelectionStyle.Blue; }
public MenuElement(string title, UIImage image, Func<UIViewController> tapped) : base(string.Empty) { _title = title; _image = image; _tappedFunc = tapped; }
public byte[] ResizeImage(byte[] imageData, float widthScale, float heightScale) { UIImage originalImage = ImageFromByteArray(imageData); UIImageOrientation orientation = originalImage.Orientation; var width = (int)(originalImage.Size.Width * widthScale); var height = (int)(originalImage.Size.Height * heightScale); //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, 4 * (int)width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { RectangleF imageRect = new RectangleF(0, 0, width, height); // draw the image context.DrawImage(imageRect, originalImage.CGImage); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); // pngとしたときのバイト配列を返す return(resizedImage.AsPNG().ToArray()); } }
public static UIImage FilteredImage (UIImage image) { var progress = NSProgress.FromTotalUnitCount (-1); progress.Cancellable = false; progress.Pausable = false; UIImage outputImage; var filter = new CIPhotoEffectTransfer (); var cgImage = image.CGImage; var ciImage = CIImage.FromCGImage (cgImage); filter.SetValueForKey (ciImage, new NSString ("inputImage")); var outputCIImage = filter.OutputImage; var ciContext = CIContext.Create (); var outputCGImage = ciContext.CreateCGImage (outputCIImage, outputCIImage.Extent); outputImage = UIImage.FromImage (outputCGImage); outputCGImage.Dispose (); ciContext.Dispose (); outputCIImage.Dispose (); ciImage.Dispose (); cgImage.Dispose (); filter.Dispose (); progress.CompletedUnitCount = 1; progress.TotalUnitCount = 1; return outputImage; }
private void BarcodeScan() { scanner = new MobileBarcodeScanner(this.NavigationController); //buttonDefaultScan = new UIButton(UIButtonType.RoundedRect); //buttonDefaultScan.Frame = new RectangleF(40, 150, 280, 40); // buttonDefaultScan = new UIButton(UIButtonType.Custom) { // Frame = new CGRect(View.Center.X - (View.Bounds.Width - 40) / 2, View.Center.Y - 50, View.Bounds.Width - 40, 100), // BackgroundColor = UIColor.FromRGB(0, 0.5f, 0), // }; UIButton buttonDefaultScan = new UIButton ( new CoreGraphics.CGRect (20, View.Center.Y - 100, View.Bounds.Width - 40, 250)); UIImage roundImage = new UIImage ("RoundButton60.png"); buttonDefaultScan.SetImage (roundImage, UIControlState.Normal); buttonDefaultScan.BackgroundColor = UIColor.Clear; // BizappTheme.Apply (buttonDefaultScan); //buttonDefaultScan.Frame = new RectangleF(40, View.Bounds.Height/2.0f, 280, 40); // buttonDefaultScan.SetTitle("Scan Barcode", UIControlState.Normal); buttonDefaultScan.TouchUpInside += async (sender, e) => { //Tell our scanner to use the default overlay scanner.UseCustomOverlay = false; //We can customize the top and bottom text of the default overlay scanner.TopText = "Hold camera up to barcode to scan"; scanner.BottomText = "Barcode will automatically scan"; //Start scanning var result = await scanner.Scan (); HandleScanResult(result); }; this.View.AddSubview (buttonDefaultScan); }
public MenuElement(string title, UIImage image, Action tapped) : base(string.Empty) { _title = title; _image = image; _tappedAction = tapped; }
public async Task<bool> Recognise (CIImage image) { if (image == null) throw new ArgumentNullException ("image"); if (_busy) return false; _busy = true; try { return await Task.Run (() => { using (var blur = new CIGaussianBlur ()) using (var context = CIContext.Create ()) { blur.SetDefaults (); blur.Image = image; blur.Radius = 0; using (var outputCiImage = context.CreateCGImage (blur.OutputImage, image.Extent)) using (var newImage = new UIImage (outputCiImage)) { _api.Image = newImage; _api.Recognize (); return true; } } }); } finally { _busy = false; } }
public byte[] ResizeImage(byte[] imageData) { UIImage originalImage = ImageFromByteArray(imageData); UIImageOrientation orientation = originalImage.Orientation; int width = (int)originalImage.Size.Width; int height = (int)originalImage.Size.Height; //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, (int)(4 * width), CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { RectangleF imageRect = new RectangleF(0, 0, width, height); // draw the image context.DrawImage(imageRect, originalImage.CGImage); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); // save the image as a jpeg return(resizedImage.AsJPEG().ToArray()); } }
public async System.Threading.Tasks.Task <byte[]> ResizeImage(byte[] imageStream, float width, float height) { //Create image using byte array... UIImage originalImage = ImageFromByteArray(imageStream); //Send image for roation... if its not up... byte[] rotatedimg = RotateImage(originalImage); //Create a new image with the byte array returned from RotateImage()... UIImage newimage = ImageFromByteArray(rotatedimg); //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, (int)(4 * width), CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { CGRect imageRect = new CGRect(0, 0, width, height); // draw the image context.DrawImage(imageRect, newimage.CGImage); //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage()); // save the image as a jpeg return(resizedImage.AsJPEG().ToArray()); } }
public System.IO.Stream RenderToStream (byte[] documentData, int pageIndex) { using (MemoryStream ms = new MemoryStream (documentData)) { // open document using (Document doc = new Document (ms)) { // prepare for rendering int width = (int)doc.Pages [pageIndex].Width; int height = (int)doc.Pages [pageIndex].Height; // render the page to a raw bitmap data represented by byte array byte[] imageData = ConvertBGRAtoRGBA(doc.Pages [pageIndex].RenderAsBytes (width,height, new RenderingSettings (), null)); // create CGDataProvider which will serve CGImage creation CGDataProvider dataProvider = new CGDataProvider (imageData, 0, imageData.Length); // create core graphics image using data provider created above, note that // we use CGImageAlphaInfo.Last(ARGB) pixel format CGImage cgImage = new CGImage(width,height,8,32,width*4,CGColorSpace.CreateDeviceRGB(),CGImageAlphaInfo.Last,dataProvider,null,false, CGColorRenderingIntent.Default); // create UIImage and save it to gallery UIImage finalImage = new UIImage (cgImage); return finalImage.AsPNG ().AsStream(); } } }
public Header() { ClipsToBounds = true; _label = this.Add<UILabel>(); _imageCollapsed = UIImage.FromBundle("collapsed-left"); _imageExpanded = UIImage.FromBundle("expanded-down"); _imageView = new UIImageView(_imageCollapsed); Add(_imageView); const int margin = 10; _imageView .Anchor(NSLayoutAttribute.Top, this, NSLayoutAttribute.Top, margin) .Anchor(NSLayoutAttribute.Right, this, NSLayoutAttribute.Right, -margin) .Anchor(NSLayoutAttribute.Bottom, this, NSLayoutAttribute.Bottom, -margin) .Layout(NSLayoutAttribute.Height, _imageView.Image.Size.Height) .Layout(NSLayoutAttribute.Width, _imageView.Image.Size.Width); _label .Anchor(NSLayoutAttribute.Left, this, NSLayoutAttribute.Left, margin) .Anchor(NSLayoutAttribute.CenterY, this, NSLayoutAttribute.CenterY) .Anchor(NSLayoutAttribute.Right, _imageView, NSLayoutAttribute.Left, -margin); }
private void CalculateLuminance(UIImage d) { var imageRef = d.CGImage; var width = (int)imageRef.Width; var height = (int)imageRef.Height; var colorSpace = CGColorSpace.CreateDeviceRGB(); var rawData = Marshal.AllocHGlobal(height * width * 4); try { var flags = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little; var context = new CGBitmapContext(rawData, width, height, 8, 4 * width, colorSpace, (CGImageAlphaInfo)flags); context.DrawImage(new CGRect(0.0f, 0.0f, (float)width, (float)height), imageRef); var pixelData = new byte[height * width * 4]; Marshal.Copy(rawData, pixelData, 0, pixelData.Length); CalculateLuminance(pixelData, BitmapFormat.BGRA32); } finally { Marshal.FreeHGlobal(rawData); } }
void AddCustomAnnotation(ShinobiChart chart) { // Create an annotation SChartAnnotationZooming an = new SChartAnnotationZooming { XAxis = chart.XAxis, YAxis = chart.YAxis, // Set its location - using the data coordinate system XValue = dateFormatter.Parse ("01-01-2009"), YValue = new NSNumber(250), // Pin all four corners of the annotation so that it stretches XValueMax = dateFormatter.Parse ("01-01-2011"), YValueMax = new NSNumber(550), // Set bounds Bounds = new CGRect (0, 0, 50, 50), Position = SChartAnnotationPosition.BelowData }; // Add some custom content to the annotation UIImage image = new UIImage ("Apple.png"); UIImageView imageView = new UIImageView (image) { Alpha = 0.1f }; an.AddSubview (imageView); // Add to the chart chart.AddAnnotation (an); }
public static UIImage ToSepia(UIImage source) { using (var filter = new CISepiaTone() { Intensity = 0.8f }) { return ColorSpaceTransformation.ToFilter(source, filter); } }
void DownLoadImageWithURL(string url) { var request = NSMutableUrlRequest.FromUrl (new NSUrl(url)); NSUrlResponse response; NSError error; NSData data = NSUrlConnection.SendSynchronousRequest (request, out response, out error); if (error == null) { image = new UIImage (data); } else { image = new UIImage (); } // NSUrlConnection.SendAsynchronousRequest (request, NSOperationQueue.MainQueue, (NSUrlResponse response, NSData data, NSError error) => { // if (error == null) // { // UIImage image = new UIImage(data); // imageView.Image = image; //// if(tableView.images.ElementAt(index) == null) //// { //// tableView.images[index] = image; //// tableView.Parent.View.EventImages.First(ei => ei.thumbnailFile == url).ImageAsNativeControl = image; //// } // completionBlock(true,image); // } else{ // completionBlock(false,null); // } // }); }
public async Task <byte[]> RotateImageAsync(byte[] originalImage , SideOrientation orientation, ImageFormat imageFormat) { byte[] resulImage = null; UIKit.UIImage uiImage = await originalImage.ToImageAsync(); CGBitmapContext bitmapContext = new CGBitmapContext(IntPtr.Zero, (int)uiImage.Size.Height, (int)uiImage.Size.Width, uiImage.CGImage.BitsPerComponent, uiImage.CGImage.BytesPerRow, uiImage.CGImage.ColorSpace, uiImage.CGImage.AlphaInfo); bitmapContext.RotateCTM(orientation == SideOrientation.RotateToRigth ? (-(float)Math.PI / 2) : (float)Math.PI / 2); bitmapContext.TranslateCTM(orientation == SideOrientation.RotateToRigth ? -(int)uiImage.Size.Width : 0, orientation == SideOrientation.RotateToRigth ? 0 : -(int)uiImage.Size.Height); bitmapContext.DrawImage(new CoreGraphics.CGRect(0, 0, (int)uiImage.Size.Width, (int)uiImage.Size.Height), uiImage.CGImage); UIImage resultUIImage = UIImage.FromImage(bitmapContext.ToImage()); if (imageFormat == ImageFormat.JPG) { resulImage = resultUIImage.AsJPEG().ToArray(); } else { resulImage = resultUIImage.AsPNG().ToArray(); } return(resulImage); }
public static FileStream ResizeImageIOS(Stream imageData, float width, float height) { UIImage originalImage = ImageFromByteArray(imageData); UIImageOrientation orientation = originalImage.Orientation; //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, 4 * (int)width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { RectangleF imageRect = new RectangleF(0, 0, width, height); // draw the image context.DrawImage(imageRect, originalImage.CGImage); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); string path = Path.Combine(Kit.Tools.Instance.TemporalPath, $"{Guid.NewGuid():N}.jpeg"); using (FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (MemoryStream memoryStream = new MemoryStream(resizedImage.AsJPEG().ToArray())) { memoryStream.Position = 0; memoryStream.CopyTo(fileStream); return(fileStream); } } // save the image as a jpeg } }
public override void ViewDidLoad() { base.ViewDidLoad (); imageView = new UIImageView(new CGRect(0, 100, 50, 50)); image = UIImage.FromFile("Sample.png"); imageView.Image = image; View.AddSubview(imageView); pt = imageView.Center; UIView.BeginAnimations ("slideAnimation"); UIView.SetAnimationDuration (2); UIView.SetAnimationCurve (UIViewAnimationCurve.EaseInOut); UIView.SetAnimationRepeatCount (2); UIView.SetAnimationRepeatAutoreverses (true); UIView.SetAnimationDelegate (this); UIView.SetAnimationDidStopSelector (new Selector ("animationDidStop:finished:context:")); var xpos = UIScreen.MainScreen.Bounds.Right - imageView.Frame.Width / 2; var ypos = imageView.Center.Y; imageView.Center = new CGPoint (xpos, ypos); UIView.CommitAnimations (); }
public RatingConfig(UIImage emptyImage, UIImage filledImage, UIImage chosenImage) { EmptyImage = emptyImage; FilledImage = filledImage; ChosenImage = chosenImage; ScaleSize = 5; ItemPadding = 0f; }
public async Task <byte[]> ResizeImageAsync(byte[] imageData, float width, float height) { await Task.Run(() => { UIImage originalImage = ImageFromByteArray(imageData); UIImageOrientation orientation = originalImage.Orientation; //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, 4 * (int)width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { RectangleF imageRect = new RectangleF(0, 0, width, height); // draw the image context.DrawImage(imageRect, originalImage.CGImage); resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); } }); // save the image as a jpeg return(resizedImage.AsPNG().ToArray()); }
public EmptyListView(UIImage image, string emptyText) : base(new CGRect(0, 0, 320f, 480f * 2f)) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; ImageView = new UIImageView(); Title = new UILabel(); ImageView.Frame = new CGRect(0, 0, 64f, 64f); ImageView.TintColor = DefaultColor; ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; ImageView.Center = new CGPoint(Frame.Width / 2f, (Frame.Height / 4f) - (ImageView.Frame.Height / 2f)); ImageView.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin; ImageView.Image = image; Add(ImageView); Title.Frame = new CGRect(0, 0, 256f, 20f); Title.Center = new CGPoint(Frame.Width / 2f, ImageView.Frame.Bottom + 30f); Title.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; Title.Text = emptyText; Title.TextAlignment = UITextAlignment.Center; Title.Font = UIFont.PreferredHeadline; Title.TextColor = DefaultColor; Add(Title); BackgroundColor = UIColor.White; }
public void Add(string key, UIImage value) { if (string.IsNullOrWhiteSpace(key) || value == null) return; _cache.SetCost(value, new NSString(key), value.GetMemorySize()); }
public Composer () : base (null, null) { Title = "New Comment"; EdgesForExtendedLayout = UIRectEdge.None; var close = new UIBarButtonItem { Image = Images.Buttons.Cancel }; NavigationItem.LeftBarButtonItem = close; SendItem = new UIBarButtonItem { Image = Images.Buttons.Save }; NavigationItem.RightBarButtonItem = SendItem; TextView = new UITextView(ComputeComposerSize(CGRect.Empty)); TextView.Font = UIFont.PreferredBody; TextView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; // Work around an Apple bug in the UITextView that crashes if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) TextView.AutocorrectionType = UITextAutocorrectionType.No; View.AddSubview (TextView); _normalButtonImage = ImageFromColor(UIColor.White); _pressedButtonImage = ImageFromColor(UIColor.FromWhiteAlpha(0.0f, 0.4f)); OnActivation(d => { d(close.GetClickedObservable().Subscribe(_ => CloseComposer())); d(SendItem.GetClickedObservable().Subscribe(_ => PostCallback())); }); }
/// <summary> /// Updates or creates a sublayer to render a border-like shape. /// </summary> /// <param name="owner">The parent layer to apply the shape</param> /// <param name="area">The rendering area</param> /// <param name="background">The background brush</param> /// <param name="borderThickness">The border thickness</param> /// <param name="borderBrush">The border brush</param> /// <param name="cornerRadius">The corner radius</param> /// <param name="backgroundImage">The background image in case of a ImageBrush background</param> /// <returns>An updated BoundsPath if the layer has been created or updated; null if there is no change.</returns> public CGPath UpdateLayer( _View owner, Brush background, BackgroundSizing backgroundSizing, Thickness borderThickness, Brush borderBrush, CornerRadius cornerRadius, _Image backgroundImage) { // Bounds is captured to avoid calling twice calls below. var bounds = owner.Bounds; var area = new CGRect(0, 0, bounds.Width, bounds.Height); var newState = new LayoutState(area, background, backgroundSizing, borderThickness, borderBrush, cornerRadius, backgroundImage); var previousLayoutState = _currentState; if (!newState.Equals(previousLayoutState)) { #if __MACOS__ owner.WantsLayer = true; #endif _layerDisposable.Disposable = null; _layerDisposable.Disposable = InnerCreateLayer(owner as UIElement, owner.Layer, newState); _currentState = newState; } return(newState.BoundsPath); }
protected override UIImage Transform(UIImage source) { using (var colorSpace = CGColorSpace.CreateDeviceGray()) { return ColorSpaceTransformation.ToColorSpace(source, colorSpace); } }
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e) { // determine what was selected, video or image bool isImage = false; if (e.Info [UIImagePickerController.MediaType].ToString () == "public.image") { isImage = true; } // // get common info (shared between images and video) // NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl; // if (referenceURL != null) // Console.WriteLine("Url:"+referenceURL.ToString ()); // if it was an image, get the other image info if(isImage) { // get the original image originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage; if(originalImage != null) { // do something with the image imgProfilePic.Image = originalImage; // display } } else { // if it's a video UIAlertView alert = new UIAlertView ("Invalid Format", "Looks like you selected a video", null, "OK", null); alert.Show (); } // dismiss the picker imagePicker.DismissViewController (true, null); }
/// <summary> /// Save UIImage into directory /// </summary> /// <param name="image"></param> void Save(UIKit.UIImage image) { var documentsDirectory = Environment.GetFolderPath (Environment.SpecialFolder.Personal); var directoryname = Path.Combine(documentsDirectory, "FolderName"); Directory.CreateDirectory(directoryname); string jpgFile = System.IO.Path.Combine(directoryname, "image.jpg"); Foundation.NSData imgData = image.AsJPEG(); Foundation.NSError err = null; if (imgData.Save(jpgFile, false, out err)) { Console.WriteLine("saved as" + jpgFile); } else { Console.WriteLine("not saved as " + jpgFile + "because" + err.LocalizedDescription); } var alert = UIAlertController.Create("Saved Location", jpgFile, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); ShowViewController(alert, null); }
public static Image AsImage(this PlatformImage image) { return(new Image() { PlatformImage = image }); }
/// <summary> /// Creates grayscaled image from existing image. /// </summary> /// <param name="oldImage">Image to convert.</param> /// <returns>Returns grayscaled image.</returns> public static UIImage GrayscaleImage( UIImage oldImage ) { var imageRect = new RectangleF(PointF.Empty, (SizeF) oldImage.Size); CGImage grayImage; // Create gray image. using (CGColorSpace colorSpace = CGColorSpace.CreateDeviceGray()) { using (var context = new CGBitmapContext(IntPtr.Zero, (int) imageRect.Width, (int) imageRect.Height, 8, 0, colorSpace, CGImageAlphaInfo.None)) { context.DrawImage(imageRect, oldImage.CGImage); grayImage = context.ToImage(); } } // Create mask for transparent areas. using (var context = new CGBitmapContext(IntPtr.Zero, (int) imageRect.Width, (int) imageRect.Height, 8, 0, CGColorSpace.Null, CGBitmapFlags.Only)) { context.DrawImage(imageRect, oldImage.CGImage); CGImage alphaMask = context.ToImage(); var newImage = new UIImage(grayImage.WithMask(alphaMask)); grayImage.Dispose(); alphaMask.Dispose(); return newImage; } }
void Init (CKRecord record, bool onServer) { IsOnServer = onServer; Record = record; Thumbnail = LoadImage (ThumbnailKey); FullImage = LoadImage (FullsizeKey); }
public override void ViewDidLoad() { AddOption ("TKChart", useChart); AddOption ("TKCalendar", useCalendar); AddOption ("UITableView", useTableView); AddOption ("UICollectionView", useCollectionView); AddOption ("TKListView", useListView); base.ViewDidLoad (); string[] imageNames = new string[] {"CENTCM.jpg", "FAMIAF.jpg", "CHOPSF.jpg", "DUMONF.jpg", "ERNSHM.jpg", "FOLIGF.jpg"}; string[] names = new string[] { "John", "Abby", "Phill", "Saly", "Robert", "Donna" }; NSMutableArray array = new NSMutableArray (); Random r = new Random (); for (int i = 0; i < imageNames.Length; i++) { UIImage image = new UIImage (imageNames [i]); this.AddItem (array, names [i], r.Next (100), r.Next (100) > 50 ? "two" : "one", r.Next (10), image); } this.dataSource.DisplayKey = "Name"; this.dataSource.ValueKey = "Value"; this.dataSource.ItemSource = array; this.useChart (this, EventArgs.Empty); }
public override void AwakeFromNib () { playBtnBg = UIImage.FromFile ("play.png").StretchableImage (12, 0); pauseBtnBg = UIImage.FromFile ("pause.png").StretchableImage (12, 0); _playButton.SetImage (playBtnBg, UIControlState.Normal); _duration.AdjustsFontSizeToFitWidth = true; _currentTime.AdjustsFontSizeToFitWidth = true; _progressBar.MinValue = 0; var fileUrl = NSBundle.MainBundle.PathForResource ("sample", "m4a"); player = AVAudioPlayer.FromUrl (new NSUrl (fileUrl, false)); player.FinishedPlaying += delegate(object sender, AVStatusEventArgs e) { if (!e.Status) Console.WriteLine ("Did not complete successfully"); player.CurrentTime = 0; UpdateViewForPlayerState (); }; player.DecoderError += delegate(object sender, AVErrorEventArgs e) { Console.WriteLine ("Decoder error: {0}", e.Error.LocalizedDescription); }; player.BeginInterruption += delegate { UpdateViewForPlayerState (); }; player.EndInterruption += delegate { StartPlayback (); }; _fileName.Text = String.Format ("Mono {0} ({1} ch)", Path.GetFileName (player.Url.RelativePath), player.NumberOfChannels); UpdateViewForPlayerInfo (); UpdateViewForPlayerState (); }
protected override void OnElementChanged(ElementChangedEventArgs <SegmentView> e) { base.OnElementChanged(e); if (e.NewElement == null) { return; } if (Control == null) { _control = new UISegmentedControl(); for (int i = 0; i < Element.Children.Count; i++) { var segment = Element.Children.ElementAt(i); if (segment.Image != null) { var img = NativeImage.FromFile(((FileImageSource)segment.Image).File); img = img.Scale(new CoreGraphics.CGSize(17, 17)); // Apple docs _control.InsertSegment(img, i, false); } else { _control.InsertSegment(segment.Title, i, false); } } _control.ClipsToBounds = true; _control.TintColor = Element.TintColor.ToUIColor(); _control.SelectedSegment = Element.SelectedIndex; _control.BackgroundColor = Element.BackgroundColor.ToUIColor(); _control.Layer.MasksToBounds = true; _control.Layer.BorderColor = Element.IsBorderColorSet() ? Element.BorderColor.ToCGColor() : Element.TintColor.ToCGColor(); if (Element.IsCornerRadiusSet()) { _control.Layer.CornerRadius = Element.CornerRadius; _control.Layer.BorderWidth = (nfloat)Element.BorderWidth; } SetSelectedTextColor(); SetNativeControl(_control); } if (e.OldElement != null && _control != null) { _control.ValueChanged -= OnSelectedIndexChanged; } if (e.NewElement != null) { _control.ValueChanged += OnSelectedIndexChanged; } }
public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo) { this.ImagenEmpresa.Image = image; NSData imageData = image.AsPNG(); InfoPerifl.Empresa_Actual.Empresa_Logotipo_Perfil = new Byte[imageData.Length]; EventosVistaTrabajoDelegate.InfoEmpresa(InfoPerifl); picker.DismissViewController(true, null); }
public Stream GetJPGStreamFromByteArray(byte[] image) { // test UIKit.UIImage images = new UIKit.UIImage(Foundation.NSData.FromArray(image)); byte[] bytes = images.AsJPEG(100).ToArray(); Stream imgStream = new MemoryStream(bytes); return(imgStream); }
public LayoutState(CGRect area, Brush background, Thickness borderThickness, Brush borderBrush, CornerRadius cornerRadius, _Image backgroundImage) { Area = area; Background = background; BorderBrush = borderBrush; CornerRadius = cornerRadius; BorderThickness = borderThickness; BackgroundImage = backgroundImage; }
public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo) { ImagenPublicacion = image; btnRemoveImage.Hidden = false; btnComentar.Enabled = true; this.btnImagen.SetImage(image, UIControlState.Normal); this.btnImagen.ContentMode = UIViewContentMode.ScaleAspectFit; this.btnImagen.Enabled = true; picker.DismissViewController(true, null); }
public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo) { ImagenPublicacion = ImageHelper.ReescalImage(image); this.btnImageComment.SetImage(image, UIControlState.Normal); this.btnDeleteImge.Hidden = false; this.btnPublicar.Enabled = true; this.btnImageComment.ContentMode = UIViewContentMode.ScaleAspectFit; this.btnImageComment.Enabled = true; picker.DismissViewController(true, null); }
public static byte[] ScaleImage(byte[] originalImage, double finalImagePercentage) { UIKit.UIImage uiImage = originalImage.ToImage(); nfloat width = uiImage.Size.Width; nfloat height = uiImage.Size.Height; int scaleWidth = Convert.ToInt16(width * (finalImagePercentage * .01)); int scaleHeight = Convert.ToInt16(height * (finalImagePercentage * .01)); return(ResizeImage(originalImage, scaleHeight, scaleWidth)); }
/// <summary> /// Scales an image. /// </summary> /// <returns>The scaled image.</returns> /// <param name="originalImage">Original image.</param> /// <param name="finalImagePercentage">Final image percentage.</param> /// <param name="imageFormat">Image format Jpg or Png.</param> public async Task <byte[]> ScaleImageAsync(byte[] originalImage, double finalImagePercentage, ImageFormat imageFormat) { UIKit.UIImage uiImage = await originalImage.ToImageAsync(); nfloat width = uiImage.Size.Width; nfloat height = uiImage.Size.Height; int scaleWidth = Convert.ToInt16(width * (finalImagePercentage * .01)); int scaleHeight = Convert.ToInt16(height * (finalImagePercentage * .01)); return(await ResizeImageAsync(originalImage, scaleHeight, scaleWidth, imageFormat)); }
public byte[] ResizeImage(byte[] imageData, float width, float height) { UIImage originalImage = ImageFromByteArray(imageData); UIImageOrientation orientImg = originalImage.Orientation; float oldWidth = (float)originalImage.Size.Width; float oldHeight = (float)originalImage.Size.Height; float scaleFactor = 0f; if (oldWidth > oldHeight) { scaleFactor = width / oldWidth; } else { scaleFactor = height / oldHeight; } float newHeight = oldHeight * scaleFactor; float newWidth = oldWidth * scaleFactor; //create a 24bit RGB image using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)newWidth, (int)newHeight, 8, (int)(4 * newWidth), CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { RectangleF imageRect = new RectangleF(0, 0, newWidth, newHeight); // draw the image context.DrawImage(imageRect, originalImage.CGImage); //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage()); //Das skalierte Bild um 90 Grad drehen //UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 1, UIImageOrientation.Right); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 1, orientImg); //Das gedrehte Bild neu rendern, höhe und Breite vertauscht um das Seitenverhältniss beizubehalten UIGraphics.BeginImageContextWithOptions(new CGSize((float)resizedImage.CGImage.Height, (float)resizedImage.CGImage.Width), true, 1.0f); //TODO: Height und Width sind evtl. vertauscht resizedImage.Draw(new CGRect(0, 0, (float)resizedImage.CGImage.Height, (float)resizedImage.CGImage.Width)); //TODO: Height und Width sind evtl. vertauscht var resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); resizedImage = resultImage; return(resizedImage.AsJPEG(100).ToArray()); // save the image as a jpeg //return resizedImage.AsJPEG(100).ToArray(); } }
public override void ViewWillAppear(bool animated) { base.ViewWillAppear(false); UIKit.UIGraphics.BeginImageContext(this.View.Frame.Size); UIKit.UIImage i = UIKit.UIImage.FromBundle("background_2_art_1.png"); i = i.Scale(this.View.Frame.Size); this.View.BackgroundColor = UIKit.UIColor.FromPatternImage(i); }
public static byte[] ResizeImage(byte[] originalImage, int newHeight, int newWidth) { byte[] resulImage = null; UIKit.UIImage uiImage = originalImage.ToImage(); UIGraphics.BeginImageContext(new CoreGraphics.CGSize(newWidth, newHeight)); uiImage.Draw(new CoreGraphics.CGRect(0, 0, newWidth, newHeight)); UIImage resultUIImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); resulImage = resultUIImage.AsJPEG().ToArray(); return(resulImage); }
private void SetImage(_Image image, bool failIfNull = true) { ImageChanged?.Invoke(image); if (image != null) { OnImageOpened(); } else if (failIfNull) { OnImageFailed(); } }
async Task <byte[]> GetImageAsByteAsync(bool usePNG, int quality, int desiredWidth, int desiredHeight) { PImage image = null; await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() => { if (Control != null) { image = Control.Image; } }).ConfigureAwait(false); if (image == null) { return(null); } if (desiredWidth != 0 || desiredHeight != 0) { image = image.ResizeUIImage((double)desiredWidth, (double)desiredHeight, InterpolationMode.Default); } #if __IOS__ NSData imageData = usePNG ? image.AsPNG() : image.AsJPEG((nfloat)quality / 100f); if (imageData == null || imageData.Length == 0) { return(null); } var encoded = imageData.ToArray(); imageData.TryDispose(); return(encoded); #elif __MACOS__ byte[] encoded; using (MemoryStream ms = new MemoryStream()) using (var stream = usePNG ? image.AsPngStream() : image.AsJpegStream(quality)) { stream.CopyTo(ms); encoded = ms.ToArray(); } if (desiredWidth != 0 || desiredHeight != 0) { image.TryDispose(); } return(encoded); #endif }
/// <summary> /// Convert byte array into UIImage /// </summary> /// <param name="bytes"></param> /// <returns></returns> private UIKit.UIImage ImageFromBytes(byte[] bytes) { try { Foundation.NSData data = Foundation.NSData.FromArray(bytes); UIKit.UIImage image = UIImage.LoadFromData(data); UIGraphics.EndImageContext(); return(image); } catch (Exception) { return(null); } }
public static byte[] ResizeImageIOS(UIImage originalImage, float width, float height) { UIImageOrientation orientation = originalImage.Orientation; using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero, (int)width, (int)height, 8, 4 * (int)width, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) { //RectangleF imageRect = new RectangleF(0, 0, width, height); //context.DrawImage(imageRect, originalImage.CGImage); UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation); return(resizedImage.AsJPEG().ToArray()); } }
public static UIKit.UIImage ImageFromByteArray(byte[] data) { if (data == null) { return(null); } UIKit.UIImage image; try { image = new UIKit.UIImage(Foundation.NSData.FromArray(data)); } catch (Exception e) { Console.WriteLine("Image load failed: " + e.Message); return(null); } return(image); }
public static UIKit.UIImage ImageFromByteArray(byte[] data) { if (data == null) { return(null); } UIKit.UIImage image; try { image = new UIKit.UIImage(Foundation.NSData.FromArray(data)); } catch (Exception e) { return(null); } return(image); }
public override void InvokedURL(WTArchitectView architectView, NSUrl url) { UIKit.UIImage test = architectView.Capture(); Console.WriteLine("architect view invoked url: " + url); // we need to fire this back to the main page so that the main page now enables the rest of the quiz pages ... MainMenuPage.SetApplicationCurrentProperty("WestAfrica", "true"); // SEND EMAIL WITH PHOTO or TWEET PHOTO HERE.... // Button emailButton = new Button { Text = "Email" }; // emailButton.Clicked += (sender, e) => // { // Device.OpenUri(new Uri("mailto:[email protected]")); // }; }
/// <summary> /// Resizes the image to have the specified maximum sizes. /// </summary> /// <param name="source">The source image to resize.</param> /// <param name="maxWidth">The max width of the image.</param> /// <param name="maxHeight">The max height of the image.</param> /// <returns>The resized image data.</returns> public override Stream ResizeImage(Stream source, int maxWidth, int maxHeight) { // Load the bitmap using (var originalBitmap = new UIKit.UIImage(NSData.FromStream(source))) { // If the image does not need to be resized var originalWidth = originalBitmap.Size.Width; var originalHeight = originalBitmap.Size.Height; if ((originalWidth <= maxWidth) && (originalHeight <= maxHeight)) { return(source); } // Calculate the resized image size var resizedHeight = (float)originalHeight; var resizedWidth = (float)originalWidth; // If height is greater than the maximum height if (resizedHeight > maxHeight) { resizedHeight = maxHeight; var factor = (float)originalHeight / maxHeight; resizedWidth = (float)originalWidth / factor; } // If the width is greater than the maximum width if (resizedWidth > maxWidth) { resizedWidth = maxWidth; var factor = (float)originalWidth / maxWidth; resizedHeight = (float)originalHeight / factor; } // Resize the image UIGraphics.BeginImageContext(new SizeF(resizedWidth, resizedHeight)); originalBitmap.Draw(new RectangleF(0, 0, resizedWidth, resizedHeight)); var resizedBitmap = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); // Save the rescaled image var imageData = resizedBitmap.AsJPEG(0.95f).ToArray(); resizedBitmap.Dispose(); return(new MemoryStream(imageData)); } }
public void FinishedPickingImage(UIKit.UIImagePickerController picker, UIKit.UIImage image, Foundation.NSDictionary editingInfo) { if (this.TouchedBack) { image = ImageHelper.ReescalProfileBackImage(image); this.btnFondoImagen.SetBackgroundImage(image, UIControlState.Normal); NewInfoPerfil.Usuario_Fotografia_FondoPerfil = image?.AsPNG().ToArray(); } else if (this.TouchedProfile) { image = ImageHelper.ReescalProfileImage(image); this.btnImagen.SetBackgroundImage(image, UIControlState.Normal); NewInfoPerfil.Usuario_Fotografia_Perfil = image?.AsPNG().ToArray(); } this.TouchedBack = false; this.TouchedProfile = false; picker.DismissViewController(true, null); }