public ItemView(Item item) { this.item = item; AddSubview (button = new UIButton { ContentMode = UIViewContentMode.ScaleAspectFill, Layer = { ShadowColor = UIColor.Black.CGColor, ShadowRadius = .3f, ShadowOpacity = .3f, ShadowOffset = new SizeF (1f, 1), }, }); button.TouchUpInside += (object sender, EventArgs e) => onTap (); button.SetImage (image = ImageLoader.Load (item.Image).ImageWithRenderingMode (UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal); label = new UILabel { AdjustsFontSizeToFitWidth = true, Font = UIFont.BoldSystemFontOfSize (100), TextAlignment = UITextAlignment.Center, Text = "0", Layer = { ShadowColor = UIColor.Black.CGColor, ShadowOpacity = .25f, ShadowRadius = .3f, ShadowOffset = new SizeF (1f, 1), } }; xScale = (float)random.NextDouble (); yScale = (float)random.NextDouble (); var s = Math.Max (random.NextDouble (), .5); scale = (float)Math.Min (s, .9); }
public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { DBError err; PhotoCell cell = (PhotoCell)collectionView.DequeueReusableCell(PhotoCell.Key, indexPath); DBPath path = Photos [Photos.Length - indexPath.Row - 1].Path; DBFile file = DBFilesystem.SharedFilesystem.OpenFile (path, out err); UIImage image = null; // This means the file doesn't exist, or it is open with asynchronous operation. if (file == null) { cell.Content = null; return cell; } if (file.Status.Cached) { image = new UIImage (file.ReadData (out err)); file.Close (); } else { file.AddObserver (this, () => { DBFileStatus newStatus = file.NewerStatus; if ((newStatus == null && file.Status.Cached) || (newStatus != null && newStatus.Cached)) { image = new UIImage (file.ReadData (out err)); cell.Content = image; file.RemoveObserver(this); file.Close (); } }); } cell.Content = image; return cell; }
public override void FinishedPickingImage (UIImagePickerController picker, UIImage image, NSDictionary editingInfo) { UIApplication.SharedApplication.SetStatusBarHidden(false, false); var imagePicker = (VCViewController)_navigationController; if (imagePicker.IsCameraAvailable) imagePicker.btnBib.Hidden = true; imagePicker.DismissModalViewControllerAnimated(true); if (imagePicker.IsCameraAvailable) { image.SaveToPhotosAlbum (delegate { // ignore errors }); } UIViewController nextScreen = null; if (tweet != null) { nextScreen = new PhotoPostViewController(_shareNavCont, image, tweet); } else { nextScreen = new PhotoLocationViewController(_shareNavCont, image); } _shareNavCont.PushViewController(nextScreen, true); }
public void UpdateWithData(Employee employee, UIImage imgDefaultAvatar, UIImage imgPhone, UIImage imgSMS, UIImage imgEmail) { avatar.Image = employee.getAvatar (); if (avatar.Image == null) { avatar.Image = imgDefaultAvatar; } name.Text = employee.getName (); title.Text = employee.title; szPhoneNo = employee.getPhoneNo (); if (szPhoneNo.Length > 0) { phoneImg.Image = imgPhone; smsImg.Image = imgSMS; } else { } szEmailAddress = employee.getEmailAddr (); if (szEmailAddress.Length > 0) { emailImg.Image = imgEmail; } else { } }
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 RectangleF (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 Scale(UIImage image, float maxWidthAndHeight) { //Perform Image manipulation, make the image fit into a 48x48 tile without clipping. UIImage scaledImage = image; image.InvokeOnMainThread(() => { float fWidth = image.Size.Width; float fHeight = image.Size.Height; float fTotal = fWidth>=fHeight?fWidth:fHeight; float fDifPercent = maxWidthAndHeight / fTotal; float fNewWidth = fWidth*fDifPercent; float fNewHeight = fHeight*fDifPercent; SizeF newSize = new SizeF(fNewWidth,fNewHeight); UIGraphics.BeginImageContext (newSize); var context = UIGraphics.GetCurrentContext (); context.TranslateCTM (0, newSize.Height); context.ScaleCTM (1f, -1f); context.DrawImage (new RectangleF (0, 0, newSize.Width, newSize.Height), image.CGImage); scaledImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); }); return scaledImage; }
public static UIImage RoundCorners (UIImage image, int radius) { if (image == null) throw new ArgumentNullException ("image"); UIImage converted = image; image.InvokeOnMainThread(() => { UIGraphics.BeginImageContext (image.Size); float imgWidth = image.Size.Width; float imgHeight = image.Size.Height; var c = UIGraphics.GetCurrentContext (); c.BeginPath (); c.MoveTo (imgWidth, imgHeight/2); c.AddArcToPoint (imgWidth, imgHeight, imgWidth/2, imgHeight, radius); c.AddArcToPoint (0, imgHeight, 0, imgHeight/2, radius); c.AddArcToPoint (0, 0, imgWidth/2, 0, radius); c.AddArcToPoint (imgWidth, 0, imgWidth, imgHeight/2, radius); c.ClosePath (); c.Clip (); image.Draw (new PointF (0, 0)); converted = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); }); return converted; }
// This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching(UIApplication app, NSDictionary options) { MonoMobileApplication.NavigationController = new UINavigationController(); _Window = new UIWindow(UIScreen.MainScreen.Bounds); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) _DefaultImage = UIImage.FromBundle("DefaultiPad.png"); else _DefaultImage = UIImage.FromBundle("Default.png"); if (_DefaultImage != null) { var imageView = new UIImageView(_Window.Bounds); imageView.Image = _DefaultImage; _Window.Add(imageView); _Window.BackgroundColor = UIColor.Clear; } MonoMobileApplication.NavigationController.View.Alpha = 0.0f; _Window.AddSubview(MonoMobileApplication.NavigationController.View); _Window.MakeKeyAndVisible(); MonoMobileApplication.Window = _Window; BeginInvokeOnMainThread(()=> { Startup(); }); return true; }
public UICitySelector() : base(UIDialogStyle.Standard, true) { this.Opacity = 0.9f; CityListBoxBackground = new UIImage(UITextBox.StandardBackground); this.Add(CityListBoxBackground); CityDescriptionBackground = new UIImage(UITextBox.StandardBackground); this.Add(CityDescriptionBackground); var script = this.RenderScript("cityselector.uis"); this.DialogSize = (Point)script.GetControlProperty("DialogSize"); var cityThumbBG = new UIImage(thumbnailBackgroundImage); cityThumbBG.Position = (Vector2)script.GetControlProperty("CityThumbnailBackgroundPosition"); this.Add(cityThumbBG); CityThumb = new UIImage(); CityThumb.Position = (Vector2)script.GetControlProperty("CityThumbnailPosition"); this.Add(CityThumb); CityDescriptionSlider.AttachButtons(CityDescriptionScrollUpButton, CityDescriptionDownButton, 1); DescriptionText.AttachSlider(CityDescriptionSlider); OkButton.Disabled = true; OkButton.OnButtonClick += new ButtonClickDelegate(OkButton_OnButtonClick); CancelButton.OnButtonClick += new ButtonClickDelegate(CancelButton_OnButtonClick); this.Caption = (string)script["TitleString"]; /** Parse the list styles **/ var listStyleNormal = script.Create<UIListBoxTextStyle>("CityListBoxColors", CityListBox.FontStyle); var listStyleBusy = script.Create<UIListBoxTextStyle>("CityListBoxColorsBusy", CityListBox.FontStyle); var listStyleFull = script.Create<UIListBoxTextStyle>("CityListBoxColorsFull", CityListBox.FontStyle); var listStyleReserved = script.Create<UIListBoxTextStyle>("CityListBoxColorsReserved", CityListBox.FontStyle); var statusToStyle = new Dictionary<CityInfoStatus, UIListBoxTextStyle>(); statusToStyle.Add(CityInfoStatus.Ok, listStyleNormal); statusToStyle.Add(CityInfoStatus.Busy, listStyleBusy); statusToStyle.Add(CityInfoStatus.Full, listStyleFull); statusToStyle.Add(CityInfoStatus.Reserved, listStyleReserved); var statusToLabel = new Dictionary<CityInfoStatus, string>(); statusToLabel.Add(CityInfoStatus.Ok, StatusOk); statusToLabel.Add(CityInfoStatus.Busy, StatusBusy); statusToLabel.Add(CityInfoStatus.Full, StatusFull); statusToLabel.Add(CityInfoStatus.Reserved, StatusOk); CityListBox.TextStyle = listStyleNormal; CityListBox.Items = NetworkFacade.Cities.Select( x => new UIListBoxItem(x, CityIconImage, x.Name, x.Online ? OnlineStatusUp : OnlineStatusDown, statusToLabel[x.Status]) { //Disabled = x.Status != TSOServiceClient.Model.CityInfoStatus.Ok, CustomStyle = statusToStyle[x.Status] } ).ToList(); CityListBox.OnChange += new ChangeDelegate(CityListBox_OnChange); //CityListBox.SelectedIndex = 0; }
public UILiveMode() { var script = this.RenderScript("livepanel"+((GlobalSettings.Default.GraphicsWidth < 1024)?"":"1024")+".uis"); Background = new UIImage(GetTexture((GlobalSettings.Default.GraphicsWidth < 1024) ? (ulong)0x000000D800000002 : (ulong)0x0000018300000002)); Background.Y = 33; this.AddAt(0, Background); var PeopleListBg = new UIImage(PeopleListBackgroundImg); PeopleListBg.Position = new Microsoft.Xna.Framework.Vector2(375, 38); this.AddAt(1, PeopleListBg); Divider = new UIImage(DividerImg); Divider.Position = new Microsoft.Xna.Framework.Vector2(140, 49); this.AddAt(1, Divider); MotiveDisplay = new UIMotiveDisplay(); MotiveDisplay.Position = new Vector2(165, 59); this.Add(MotiveDisplay); EODHelpButton.Visible = false; EODCloseButton.Visible = false; EODExpandButton.Visible = false; EODContractButton.Visible = false; }
public override void AwakeFromNib() { base.AwakeFromNib (); playBtnBG = UIImage.FromFile ("images/play.png"); pauseBtnBG = UIImage.FromFile ("images/pause.png"); playButton.SetImage (playBtnBG, UIControlState.Normal); this.registerForBackgroundNotifications (); updateTimer = null; rewTimer = null; ffwTimer = null; duration.AdjustsFontSizeToFitWidth = true; currentTime.AdjustsFontSizeToFitWidth = true; progressBar.MinValue = 0.0f; // Load the the sample file, use mono or stero sample NSUrl fileURL = NSUrl.FromFilename (NSBundle.MainBundle.PathForResource ("sample" , @"m4a")); CreateNewPlayer ( fileURL); AudioSession.Initialize(); NSError setCategoryError; AVAudioSession.SharedInstance ().SetCategory (new NSString (AVAudioSession.CategoryPlayback.ToString ()), out setCategoryError); AVAudioSession.SharedInstance ().SetActive (true, out setCategoryError); UIApplication.SharedApplication.BeginReceivingRemoteControlEvents (); if (setCategoryError != null) Console.WriteLine (@"Error setting category! {0}", setCategoryError); AudioSession.AddListener (AudioSessionProperty.AudioRouteChange, RouteChangeListener); }
public StyledElement(string caption, NSAction tapped, UIImage image) : base(caption, tapped) { Init(); Image = image; Accessory = UITableViewCellAccessory.DisclosureIndicator; }
public static DumpValue AsImage(UIImage image) { var data = image.AsJPEG(0.6f); var dataBytes = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length)); return new DumpValue { TypeName = "___IMAGE___", DumpType = DumpValue.DumpTypes.Image, PrimitiveValue = Convert.ToBase64String(dataBytes) }; }
public StringElement (string caption, string value, UIImage image, Action tapped) : base(caption) { Tapped += tapped; this.Value = value; this.Image = image; }
public override void ViewWillLayoutSubviews() { base.ViewWillLayoutSubviews(); try { if (_imgView != null) _imgView.Frame = this.View.Bounds; if (_img != null) _img.Dispose(); _img = null; //Load the background image if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { _img = UIImageHelper.FromFileAuto(Utilities.IsTall ? "Default-568h" : "Default"); } else { if (UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.Portrait || UIApplication.SharedApplication.StatusBarOrientation == UIInterfaceOrientation.PortraitUpsideDown) _img = UIImageHelper.FromFileAuto("Default-Portrait"); else _img = UIImageHelper.FromFileAuto("Default-Landscape"); } if (_img != null && _imgView != null) _imgView.Image = _img; } catch (Exception e) { Utilities.LogException("Unable to show StartupController", e); } }
public override void AwakeFromNib () { playBtnBg = UIImage.FromFile ("images/play.png").StretchableImage (12, 0); pauseBtnBg = UIImage.FromFile ("images/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 (); }
public static void SetStretchableImage(this UIImageView view, string imagePath) { var normalImage = new UIImage (imagePath); var stretchableNormalImage = UIImage.FromBundle (imagePath).StretchableImage((int) (normalImage.Size.Width/2 - 1), (int)(normalImage.Size.Height/2 - 1)); view.Image = stretchableNormalImage; }
/// <summary> /// Gets the default image. /// </summary> /// <returns>The default image.</returns> private static UIImage GetDefaultImage() { if (_defaultImage == null) { _defaultImage = UIImage.FromFile ("Images/marker-and-shadow.png"); } return _defaultImage; }
public MenuItem(UIImage image, UIImage highlightImage, UIImage contentImage, UIImage highlightContentImage) : base() { this.Image = image; this.HighlightedImage = highlightImage; this.UserInteractionEnabled = true; // figure this out if (contentImage == null) { contentImage = image; } if (contentImage != null) { this.contentImageView = new UIImageView(contentImage); if (highlightContentImage != null) { this.contentImageView.HighlightedImage = highlightContentImage; } this.AddSubview(this.contentImageView); } }
public MenuItem(UIImage image, UIImage highlightImage) : base() { this.Image = image; this.HighlightedImage = highlightImage; this.UserInteractionEnabled = true; }
public UIInbox() { var script = this.RenderScript("messageinbox.uis"); Background = new UIImage(backgroundImage); this.AddAt(0, Background); CloseButton.OnButtonClick += new ButtonClickDelegate(Close); UIUtils.MakeDraggable(Background, this); MessageButton.OnButtonClick += new ButtonClickDelegate(MessageButton_OnButtonClick); var msgStyleCSR = script.Create<UIListBoxTextStyle>("CSRMessageColors", InboxListBox.FontStyle); var msgStyleServer = script.Create<UIListBoxTextStyle>("ServerMessageColors", InboxListBox.FontStyle); var msgStyleGame = script.Create<UIListBoxTextStyle>("GameMessageColors", InboxListBox.FontStyle); var msgStyleSim = script.Create<UIListBoxTextStyle>("SimMessageColors", InboxListBox.FontStyle); var msgStyleClub = script.Create<UIListBoxTextStyle>("ClubMessageColors", InboxListBox.FontStyle); var msgStyleProperty = script.Create<UIListBoxTextStyle>("PropertyMessageColors", InboxListBox.FontStyle); var msgStyleNeighborhood = script.Create<UIListBoxTextStyle>("NeighborhoodMessageColors", InboxListBox.FontStyle); var item = new UIListBoxItem("idk", "!", "", "||", "", "21:21 - 4/2/2014", "", "The Sims Online", "", "Please stop remaking our game"); item.CustomStyle = msgStyleSim; InboxListBox.Items.Add(item); Dropdown = new UIInboxDropdown(); Dropdown.X = 162; Dropdown.Y = 13; this.Add(Dropdown); }
public ADVPopoverProgressBar(RectangleF frame, ADVProgressBarColor barColor): base(frame) { bgImageView = new UIImageView(new RectangleF(0, 0, frame.Width, 24)); bgImageView.Image = UIImage.FromFile("progress-track.png"); this.AddSubview(bgImageView); progressFillImage = UIImage.FromFile("progress-fill.png").CreateResizableImage(new UIEdgeInsets(0, 20, 0, 40)); progressImageView = new UIImageView(new RectangleF(-2, 0, 0, 32)); this.AddSubview(progressImageView); percentView = new UIView(new RectangleF(5, 4, PERCENT_VIEW_WIDTH, 15)); percentView.Hidden = true; UILabel percentLabel = new UILabel(new RectangleF(0, 0, PERCENT_VIEW_WIDTH, 14)); percentLabel.Tag = 1; percentLabel.Text = "0%"; percentLabel.BackgroundColor = UIColor.Clear; percentLabel.TextColor = UIColor.Black; percentLabel.Font = UIFont.BoldSystemFontOfSize(11); percentLabel.TextAlignment = UITextAlignment.Center; percentLabel.AdjustsFontSizeToFitWidth = true; percentView.AddSubview(percentLabel); this.AddSubview(percentView); }
public void UpdateCell(string team1Name, string team2Name, string headerText, int team1Score, int team2Score, UIImage team1Image, UIImage team2Image) { try { team1ImageView.Image = team1Image; team2ImageView.Image = team2Image; _team1Name.Text = team1Name; _team2Name.Text = team2Name; _team1Score.Text = team1Score.ToString(); _team2Score.Text = team2Score.ToString(); if (team1Score > team2Score) { _team1Score.TextColor = UIColor.Purple; _team2Score.TextColor = UIColor.Black; } else { _team1Score.TextColor = UIColor.Black; _team2Score.TextColor = UIColor.Purple; } _headingLabel.Text = headerText; Accessory = UITableViewCellAccessory.None; } catch (Exception exception) { ErrorHandler.Save(exception, MobileTypeEnum.iPhone); } }
public override void ViewDidLoad () { var ok = new UIImage("Images/Icons/icon_checked.png"); var notOk = new UIImage("Images/Icons/icon_unchecked.png"); imgArt.Image = _logg.ArtId > 0 ? ok : notOk; imgJeger.Image = _logg.JegerId > 0 ? ok : notOk; imgNotater.Image = _logg.Notes.Length > 0 ? ok : notOk; imgPosisjon.Image = _logg.Latitude.Length > 0 ? ok : notOk; imgSkudd.Image = _logg.Skudd > 0 ? ok : notOk; imgBilde.Image = _logg.ImagePath.Length > 0 ? ok : notOk; var imgstr = Utils.GetPath("jaktlogg_"+_logg.ID+".jpg"); if(!File.Exists(imgstr)){ imgstr = "Images/Icons/pictureplaceholder.png"; buttonImage.SetImage(new UIImage(imgstr), UIControlState.Normal); } else buttonImage.SetImage(new UIImage(Utils.GetPath(imgstr)), UIControlState.Normal); buttonImage.Layer.MasksToBounds = true; buttonImage.Layer.CornerRadius = 5.0f; buttonImage.TouchUpInside += HandleButtonImageTouchUpInside; base.ViewDidLoad (); }
private void HandleImagePick(UIImage image, int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { if (image != null) { // resize the image image = image.ImageToFitSize (new SizeF (maxPixelDimension, maxPixelDimension)); using (NSData data = image.AsJPEG ((float)((float)percentQuality/100.0))) { var byteArray = new byte [data.Length]; Marshal.Copy (data.Bytes, byteArray, 0, Convert.ToInt32 (data.Length)); var imageStream = new MemoryStream (); imageStream.Write (byteArray, 0, Convert.ToInt32 (data.Length)); imageStream.Seek (0, SeekOrigin.Begin); pictureAvailable (imageStream); } } else { assumeCancelled (); } _picker.DismissModalViewControllerAnimated(true); _presenter.NativeModalViewControllerDisappearedOnItsOwn(); }
private void CalculateLuminance(UIImage d) { var imageRef = d.CGImage; var width = imageRef.Width; var height = 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 RectangleF(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); } }
public UIUCP() { this.RenderScript("ucp.uis"); Background = new UIImage(BackgroundGameImage); this.AddAt(0, Background); Background.BlockInput(); BackgroundMatchmaker = new UIImage(BackgroundMatchmakerImage); BackgroundMatchmaker.Y = 81; this.AddAt(0, BackgroundMatchmaker); BackgroundMatchmaker.BlockInput(); TimeText.Caption = "12:00 am"; MoneyText.Caption = "§0"; CurrentPanel = -1; OptionsModeButton.OnButtonClick += new ButtonClickDelegate(OptionsModeButton_OnButtonClick); ZoomOutButton.OnButtonClick += new ButtonClickDelegate(ZoomControl); ZoomInButton.OnButtonClick += new ButtonClickDelegate(ZoomControl); NeighborhoodButton.OnButtonClick += new ButtonClickDelegate(SetCityZoom); WorldButton.OnButtonClick += new ButtonClickDelegate(SetCityZoom); PhoneButton.OnButtonClick += new ButtonClickDelegate(PhoneButton_OnButtonClick); SetInLot(false); SetMode(UCPMode.CityMode); }
void CompletedHandler(UIImage image, NSError error, SDImageCacheType cacheType) { if (activityIndicator != null) { activityIndicator.RemoveFromSuperview (); activityIndicator = null; } }
public static UIImage Filter(UIImage img, int puzzleSize) { int tileSize = 2; int paletteColorsNumber = BasePaletteColorsNumber + (8 * puzzleSize / 64); // 1/ Get the main colors // So we have a color palette Logger.I ("Filter: getting palette..."); var colorPalette = getColorPalette (img, paletteColorsNumber); // 1/ Resize & Load image as readable UIImage resizedImg = UIImageEx.ResizeRatio (img, puzzleSize); Bitmap bitmap = new Bitmap (resizedImg); // 2/ Apply mosaic Logger.I ("Filter: applying mosaic..."); var flippedImage = applyMosaic (tileSize, colorPalette, resizedImg, bitmap); // -- Flip because bitmap has inverted coordinates Logger.I ("Filter: resizing..."); UIImage finalImg = new UIImage (flippedImage, 0f, UIImageOrientation.DownMirrored); // UIImage finalImg = new UIImage (flippedImage); // -- Resize the final // return ResizeRatio (finalImg, FinalSize); Logger.I ("Filter: image ready!"); return finalImg; }
public void UpdateCell(string name, string text, UIImage image, DateTime created) { imageView.Image = image; _headingLabel.Text = name; _subheadingLabel.Text = text; _createdLable.Text = ParseDate (created); }
public PlayerInfo(int playerIndex, bool offlineUser) { if (!offlineUser) { this.player = HEROsModNetwork.Network.Players[playerIndex]; } this.playerIndex = playerIndex; this.UpdateWhenOutOfBounds = true; Width = 350; UIImage bClose = new UIImage(closeTexture); UILabel lGroup = new UILabel("Group:"); UIButton bBan = new UIButton("Ban"); UIButton bKick = new UIButton("Kick"); UILabel label = new UILabel(); SnoopWindow snoopWindow = new SnoopWindow(); snoopWindow.SetPlayer(Main.player[0]); dropdown = new UIDropdown(); UIButton bTeleport = new UIButton("Teleport To"); UIButton bRestore = new UIButton("Restore Changes Made by this Player"); bTeleport.AutoSize = false; bTeleport.Width = 150; bRestore.AutoSize = false; // if logged in if (player != null && player.Username.Length > 0) { dropdown.AddItem(HEROsModNetwork.Network.AdminGroup.Name); for (int i = 0; i < HEROsModNetwork.Network.Groups.Count; i++) { dropdown.AddItem(HEROsModNetwork.Network.Groups[i].Name); if (player.Group.Name == HEROsModNetwork.Network.Groups[i].Name) { dropdown.SelectedItem = i + 1; } } } else if (player == null) { HEROsModNetwork.UserWithID user = HEROsModNetwork.Network.RegisteredUsers[playerIndex]; dropdown.AddItem(HEROsModNetwork.Network.AdminGroup.Name); for (int i = 0; i < HEROsModNetwork.Network.Groups.Count; i++) { dropdown.AddItem(HEROsModNetwork.Network.Groups[i].Name); if (user.groupID == HEROsModNetwork.Network.Groups[i].ID) { dropdown.SelectedItem = i + 1; } } } dropdown.selectedChanged += dropdown_selectedChanged; bClose.Y = spacing; lGroup.Scale = .5f; lGroup.X = spacing; lGroup.Y = spacing; dropdown.X = lGroup.X + lGroup.Width + 4; dropdown.Y = lGroup.Y; dropdown.Width = 200; dropdown.UpdateWhenOutOfBounds = true; if (player != null && player.Username.Length > 0) { label.Text = "Logged in as " + player.Username; } else { label.Text = "Not Logged In"; } label.X = spacing; label.Y = dropdown.Y + dropdown.Height + spacing; label.Scale = .35f; bBan.X = label.X; bBan.Y = label.Y + label.Height + spacing; bKick.X = bBan.X + bBan.Width + spacing; bKick.Y = bBan.Y; bTeleport.X = Width - bTeleport.Width - spacing; bTeleport.Y = bBan.Y; bRestore.X = Spacing; bRestore.Y = bTeleport.Y + bTeleport.Height + spacing; snoopWindow.X = bRestore.X; snoopWindow.Y = bRestore.Y + bRestore.Height + spacing; Width = bTeleport.X + bTeleport.Width + spacing; Height = bRestore.Y + bRestore.Height + spacing; bRestore.Width = Width - spacing * 2; AddChild(bClose); AddChild(label); HEROsModNetwork.Group myGroup = HEROsModNetwork.LoginService.MyGroup; if (!offlineUser) { if (myGroup.HasPermission("TeleportToPlayers")) { AddChild(bTeleport); } if (myGroup.HasPermission("Ban")) { AddChild(bBan); } if (myGroup.HasPermission("Kick")) { AddChild(bKick); } if (myGroup.HasPermission("Snoop")) { snoopWindow.SetPlayer(Main.player[playerIndex]); AddChild(snoopWindow); Width = snoopWindow.X + snoopWindow.Width + spacing * 2; Height = snoopWindow.Y + snoopWindow.Height + spacing * 2; } } if (myGroup.IsAdmin) { AddChild(lGroup); AddChild(dropdown); if (offlineUser || player != null && player.Username.Length > 0) { //AddChild(bRestore); } } bBan.Tag = Main.player[playerIndex].name; bKick.Tag = Main.player[playerIndex].name; bClose.X = Width - bClose.Width - spacing; bKick.onLeftClick += bKick_onLeftClick; bBan.onLeftClick += bBan_onLeftClick; bClose.onLeftClick += bClose_onLeftClick; bTeleport.onLeftClick += bTeleport_onLeftClick; bRestore.onLeftClick += bRestore_onLeftClick; }
UIView GetItemView(SerializationModel model, CGRect frame) { UIButton button = new UIButton(frame); UIImageView imageView = new UIImageView(new CGRect(0, 5, frame.Width, frame.Height - 20)); imageView.Alpha = 1f; imageView.Image = model.Image; imageView.BackgroundColor = model.ImageBackgroundColor; imageView.ContentMode = model.ImageAlignment; button.AddSubview(imageView); UILabel label = new UILabel(); if (model.Name != "Create New") { label.Frame = new CGRect(0, frame.Height - 40, frame.Width, 25); label.Alpha = 0.5f; label.BackgroundColor = UIColor.LightGray; if (model.IsImageSelected) { UIImageView SelectedView = new UIImageView(new CGRect(frame.Width - 25, 10, 20, 20)); if (!model.IsItemSelectedToDelete) { SelectedView.Image = UIImage.FromBundle("Images/ImageEditor/NotSelected.png"); imageView.Alpha = 1f; } else { SelectedView.Image = UIImage.FromBundle("Images/ImageEditor/Selected.png"); imageView.Alpha = 0.3f; } SelectedView.BackgroundColor = UIColor.Clear; SelectedView.ContentMode = UIViewContentMode.ScaleAspectFit; button.AddSubview(SelectedView); } } else { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Frame = new CGRect(0, frame.Height / 2 + 50, frame.Width, 25); } else { label.Frame = new CGRect(0, frame.Height / 2 + 20, frame.Width, 25); } label.Alpha = 1f; label.BackgroundColor = UIColor.Clear; label.TextColor = UIColor.White; } label.Font = UIFont.SystemFontOfSize(18); label.TextAlignment = UITextAlignment.Center; label.Text = model.Name; button.AddSubview(label); UILongPressGestureRecognizer detector = new UILongPressGestureRecognizer((UILongPressGestureRecognizer obj) => { OnLongPressed(this, model); }); button.AddGestureRecognizer(detector); button.TouchUpInside += (sender, e) => { OnItemSelected(this, model); }; return(button); }
public override void LayoutSubviews() { base.LayoutSubviews(); CustomCollectionView.Frame = new CGRect(0, 70, Frame.Width, Frame.Height - 150); CustomCollectionView.DataSource = ViewModel.ModelCollection; CustomCollectionView.ItemSelected += (sender, e) => { var model = e as SerializationModel; ValidateItem(model); }; CustomCollectionView.LongPressed += (sender, e) => { if ((e as SerializationModel).Name != "Create New") { deleteIcon.Alpha = 1; EnableSelection(); } }; this.BackgroundColor = UIColor.FromRGB(242, 242, 242); /*------Header Label-------*/ UILabel label = new UILabel(new CGRect(20, 50, Frame.Width, 25)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextAlignment = UITextAlignment.Left; label.TextColor = UIColor.Gray; label.Text = "Serialization"; /*------Delete------------*/ deleteIcon = new UIButton(new CGRect(Frame.Width / 2 - 50, Frame.Height - 60, 100, 50)); deleteIcon.Alpha = 0; deleteIcon.BackgroundColor = UIColor.Clear; deleteIcon.TouchUpInside += (sender, e) => { for (int i = 0; i < list.Count; i++) { if (ViewModel.ModelCollection.Contains(list[i])) { ViewModel.ModelCollection.Remove(list[i]); } } foreach (var item1 in ViewModel.ModelCollection) { item1.IsImageSelected = false; item1.IsItemSelectedToDelete = false; list = new List <SerializationModel>(); } CustomCollectionView.DataSource = ViewModel.ModelCollection; deleteIcon.Alpha = 0; }; UIImageView DeleteButton = new UIImageView(new CGRect(0, 0, 100, 50)); DeleteButton.Image = UIImage.FromBundle("Images/ImageEditor/Delete1.png"); DeleteButton.ContentMode = UIViewContentMode.ScaleAspectFit; deleteIcon.AddSubview(DeleteButton); AddSubview(label); AddSubview(CustomCollectionView); AddSubview(deleteIcon); }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. this.Title = "Using Microsoft Cognitive Services API with Xamarin IOS"; SetSendButtonStates(false); var width = UIScreen.MainScreen.Bounds.Width * 0.45; var height = UIScreen.MainScreen.Bounds.Height * 0.45; CGSize imageSize = new CGSize(width, height); CGPoint imageLoc = CapturedImage.Frame.Location; CapturedImage.Frame = new CGRect(imageLoc, imageSize); CapturedImage.Layer.BorderColor = UIColor.Purple.CGColor; CapturedImage.Layer.BorderWidth = 2.0f; ImageData.Layer.BorderColor = UIColor.Purple.CGColor; ImageData.Layer.BorderWidth = 2.0f; Front.TouchUpInside += ToggleCameraSwitches; Back.TouchUpInside += ToggleCameraSwitches; if (!SettingsService.FaceAPIConfigured || !SettingsService.VisionAPIConfigured) { DisplayMessage("Settings Missing!", "One or more required settings values missing. Some features disabled. Set all fields in the settings screen to perform all functions.", "OK"); } CaptureImage.TouchUpInside += async(s, e) => { await CrossMedia.Current.Initialize(); CameraDevice camera = (Front.On ? CameraDevice.Front : CameraDevice.Rear); if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { DisplayMessage("Unavailable!", "Camera unavailable on this device! Cannot continue!", "OK"); return; } image = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { PhotoSize = PhotoSize.Custom, CustomPhotoSize = 45, DefaultCamera = camera }); if (image != null) { NSData imageData = NSData.FromStream(image.GetStream()); CapturedImage.Image = UIImage.LoadFromData(imageData); SetSendButtonStates(true); } }; ClearPicture.TouchUpInside += (s, e) => { image = null; CapturedImage.Image = null; SetSendButtonStates(false); ImageData.Text = string.Empty; }; Describe.TouchUpInside += async(s, e) => { ImageData.Text = string.Empty; if (!SettingsService.VisionAPIConfigured) { DisplayMessage( "Not configured!", "The Vision API is not correctly setup in the settings screen. Please set API Key and Endpoint.", "OK"); return; } VisionServiceClient client = new VisionServiceClient(SettingsService.VisionAPIKey, SettingsService.VisionAPIEndpoint); VisualFeature[] features = { VisualFeature.Tags, VisualFeature.Categories, VisualFeature.Description }; var result = await client.AnalyzeImageAsync(image.GetStream(), features); var analysisResult = ""; analysisResult += "Categories:\n"; foreach (Category c in result.Categories) { analysisResult += string.Format("{0} :: {1}%\n", c.Name, Math.Round(c.Score * 100, 2).ToString()); } analysisResult += "\n\nDescriptions:\n"; foreach (Caption c in result.Description.Captions) { analysisResult += string.Format("{0} :: {1}%\n", c.Text, Math.Round(c.Confidence * 100, 2).ToString()); } analysisResult += "\n\nTags:\n"; foreach (Tag t in result.Tags) { analysisResult += string.Format("{0} :: {1}%\n", t.Name, Math.Round(t.Confidence * 100, 2).ToString()); } ImageData.Text = analysisResult; }; OCR.TouchUpInside += async(s, e) => { ImageData.Text = string.Empty; if (!SettingsService.VisionAPIConfigured) { DisplayMessage( "Not configured!", "The Vision API is not correctly setup in the settings screen. Please set API Key and Endpoint.", "OK"); return; } VisionServiceClient client = new VisionServiceClient(SettingsService.VisionAPIKey, SettingsService.VisionAPIEndpoint); var result = await client.RecognizeTextAsync(image.GetStream()); var readText = ""; foreach (Region r in result.Regions) { foreach (Line l in r.Lines) { foreach (Word w in l.Words) { readText += w.Text + " "; } readText += "\n"; } } ImageData.Text = readText; }; Emotion.TouchUpInside += async(sender, e) => { ImageData.Text = string.Empty; FaceService faceClient = new FaceService(); var analysis = await faceClient.DetectAsync(image.GetStream()); var data = ""; UIColor[] borderColors = { UIColor.Red, UIColor.Green, UIColor.Purple, UIColor.Yellow }; string[] borderColorStrings = { "Red", "Green", "Purple", "Yellow" }; //counter to select the correct border color int count = 0; foreach (Helpers.Face f in analysis) { var scale = UIScreen.MainScreen.Scale; CGRect faceBorder = new CGRect(f.FaceRectangle.Left, f.FaceRectangle.Top, f.FaceRectangle.Width, f.FaceRectangle.Height); CapturedImage.Image = CapturedImage.Image.DrawRectangleOnImage(faceBorder, borderColors[count]); data += "Face ID: " + f.FaceId + "\n"; data += "Border Color: " + borderColorStrings[count] + "\n"; data += f.FaceAttributes.age.ToString() + "yo " + f.FaceAttributes.gender + "\n\n"; data += "Anger: " + Math.Round(f.FaceAttributes.emotion.anger * 100, 2).ToString() + "%\n"; data += "Contempt: " + Math.Round(f.FaceAttributes.emotion.contempt * 100, 2).ToString() + "%\n"; data += "Disgust: " + Math.Round(f.FaceAttributes.emotion.disgust * 100, 2).ToString() + "%\n"; data += "Fear: " + Math.Round(f.FaceAttributes.emotion.fear * 100, 2).ToString() + "%\n"; data += "Happiness: " + Math.Round(f.FaceAttributes.emotion.happiness * 100, 2).ToString() + "%\n"; data += "Neutral: " + Math.Round(f.FaceAttributes.emotion.neutral * 100, 2).ToString() + "%\n"; data += "Sadness: " + Math.Round(f.FaceAttributes.emotion.sadness * 100, 2).ToString() + "%\n"; data += "Surprise: " + Math.Round(f.FaceAttributes.emotion.surprise * 100, 2).ToString() + "%\n"; data += "\n\n"; //increment counter for border colors count++; } ImageData.Text = data; }; }
private void SetCustomBackButton() { // Load the Back arrow Image var backBtnImage = UIImage.FromBundle("iosbackarrow.png"); backBtnImage = backBtnImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); // Create our Button and set Edge Insets for Title and Image var backBtn = new UIButton(UIButtonType.Custom) { HorizontalAlignment = UIControlContentHorizontalAlignment.Left, TitleEdgeInsets = new UIEdgeInsets(11.5f, 15f, 10f, 0f), ImageEdgeInsets = new UIEdgeInsets(1f, 8f, 0f, 0f) }; // Set the styling for Title // You could set any Text as you wish here backBtn.SetTitle("", UIControlState.Normal); // use the default blue color in ios back button text backBtn.SetTitleColor(UIColor.White, UIControlState.Normal); backBtn.SetTitleColor(UIColor.LightGray, UIControlState.Highlighted); backBtn.Font = UIFont.FromName("HelveticaNeue", (nfloat)17); // Set the Image to the button backBtn.SetImage(backBtnImage, UIControlState.Normal); // Allow the button to Size itself backBtn.SizeToFit(); // Add the Custom Click event you would like to // execute upon the Back button click backBtn.TouchDown += (sender, e) => { // Whatever your custom back button click handling if (((CoolContentPage)Element)?.CustomBackButtonAction != null) { ((CoolContentPage)Element)?.CustomBackButtonAction.Invoke(); } }; //Set the frame of the button backBtn.Frame = new CGRect( 0, 0, UIScreen.MainScreen.Bounds.Width / 4, NavigationController.NavigationBar.Frame.Height); // Add our button to a container var btnContainer = new UIView( new CGRect(0, 0, backBtn.Frame.Width, backBtn.Frame.Height)); btnContainer.AddSubview(backBtn); // A dummy button item to push our custom back button to // the edge of screen (sort of a hack) var fixedSpace = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) { Width = -16f }; // wrap our custom back button with a UIBarButtonItem var backButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null) { CustomView = backBtn }; // Add it to the ViewController NavigationController.TopViewController.NavigationItem.LeftBarButtonItems = new[] { fixedSpace, backButtonItem }; }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. btnAdicionar.TouchUpInside += (sender, e) => { contador++; var str = "ada " + contador.ToString() + "adsas"; var sb = new StringBuilder(); sb.Append("adadasdadas"); sb.Append(contador); sb.Append("asdas"); var str2 = sb.ToString(); lblTeste.Text = String.Format("Click número {0}", contador); if (txtNumero.IsFirstResponder) { txtNumero.ResignFirstResponder(); } }; imgTeste.Image = UIImage.LoadFromData( NSData.FromUrl(NSUrl.FromString( "http://www.fillmurray.com/200/200"))); switchImg.TouchUpInside += (sender, e) => { ; imgTeste.Hidden = !switchImg.On; if (txtNumero.IsFirstResponder) { txtNumero.ResignFirstResponder(); } }; slider.TouchUpInside += (sender, e) => { txtNumero.Text = slider.Value.ToString(); if (txtNumero.IsFirstResponder) { txtNumero.ResignFirstResponder(); } }; txtNumero.Ended += (sender, e) => { if (!String.IsNullOrEmpty(txtNumero.Text)) { slider.Value = float.Parse(txtNumero.Text); } }; txtNumero.ShouldReturn = (textField) => { txtNumero.ResignFirstResponder(); return(true); }; txtNumero.TouchUpOutside += (sender, e) => { txtNumero.ResignFirstResponder(); }; txtSenha.ShouldReturn = (textField) => { txtSenha.ResignFirstResponder(); return(true); }; txtNumero.ShouldBeginEditing = (textField) => { NSNotificationCenter.DefaultCenter.AddObserver( new NSString("keyboardOn"), (obj) => { View.Frame = new CGRect(0, -110, 320, 460); }); return(true); }; txtSenha.ShouldBeginEditing = (textField) => { NSNotificationCenter.DefaultCenter.AddObserver( UIKeyboard.DidShowNotification, (obj) => { View.Frame = new CGRect(0, -110, 320, 460); }); return(true); }; txtNumero.ShouldEndEditing = (textField) => { NSNotificationCenter.DefaultCenter.AddObserver( new NSString("keyboardOff"), (obj) => { View.Frame = new CGRect(0, 0, 320, 460); }); return(true); }; txtSenha.ShouldEndEditing = (textField) => { NSNotificationCenter.DefaultCenter.AddObserver( UIKeyboard.DidHideNotification, (obj) => { View.Frame = new CGRect(0, 0, 320, 460); }); return(true); }; }
protected override void InitializeObjects() { base.InitializeObjects(); var topView = new UIView(); var scrollView = new UIScrollView(); var topTextRowView = new UIView(); var centerTextRowView = new UIView(); var bottomTextRowView = new UIView(); var bottomView = new UIView(); var profileNavigationBarBackground = new UIImageView(UIImage.FromBundle(@"Images/navigation_bar_background.png")); backHomeView = UIButton.FromType(UIButtonType.Custom); backHomeView.SetImage(UIImage.FromFile(@"Images/ic_back.png"), UIControlState.Normal); nameOfPageLabel = LabelInformationAboutPage(UIColor.White, "Profile", UIFont.BoldSystemFontOfSize(16f)); informationAboutPageLabel = LabelInformationAboutPage(UIColor.FromRGB(29, 157, 189), "Please, Enter Your Personal Information.", UIFont.FromName("Helvetica", 14f)); // Hide navigation bar NavigationController.SetNavigationBarHidden(true, false); View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile(@"Images/tab_background.png").Scale(View.Frame.Size)); profileNavigationBarBackground.Frame = new CGRect(10, 10, profileNavigationBarBackground.Image.CGImage.Width, profileNavigationBarBackground.Image.CGImage.Height); var labelView = new UIView(); labelView.AddIfNotNull(nameOfPageLabel, informationAboutPageLabel); labelView.AddConstraints( nameOfPageLabel.AtTopOf(labelView, 20), nameOfPageLabel.WithSameCenterX(labelView), nameOfPageLabel.WithSameCenterY(labelView), nameOfPageLabel.WithSameWidth(labelView), nameOfPageLabel.WithRelativeHeight(labelView, 0.3f), informationAboutPageLabel.Below(nameOfPageLabel, 5), informationAboutPageLabel.WithSameWidth(labelView), informationAboutPageLabel.WithSameCenterX(labelView), informationAboutPageLabel.WithRelativeHeight(labelView, 0.3f) ); topView.AddIfNotNull(profileNavigationBarBackground, backHomeView, labelView); topView.AddConstraints( profileNavigationBarBackground.WithSameWidth(topView), profileNavigationBarBackground.WithSameHeight(topView), profileNavigationBarBackground.AtTopOf(topView), backHomeView.WithSameCenterY(topView), backHomeView.AtLeftOf(topView, 20), backHomeView.WithRelativeWidth(topView, 0.1f), backHomeView.WithRelativeHeight(topView, 0.2f), labelView.WithSameCenterX(topView), labelView.WithSameCenterY(topView), labelView.WithRelativeWidth(topView, 0.8f), labelView.WithRelativeHeight(topView, 0.6f) ); firstNameTextField = TextFieldInitializer("First Name"); lastNameTextField = TextFieldInitializer("Last Name"); emailTextField = TextFieldInitializer("Email"); addressTextField = TextFieldInitializer("Address"); cityTextField = TextFieldInitializer("City"); zipCodeTextField = TextFieldInitializer("Zip Code"); stateTextField = TextFieldInitializer("State"); statesPicker = new UIPickerView(); statesPickerViewModel = new MvxPickerViewModel(statesPicker); statesPicker.Model = statesPickerViewModel; statesPicker.ShowSelectionIndicator = true; statesPicker.BackgroundColor = UIColor.White; addLicenseButton = ProfileButtonManager.ButtonInitiaziler("Add License Plate", UIImage.FromFile(@"Images/ProfileView/ic_license.png")); addCreditCardButton = ProfileButtonManager.ButtonInitiaziler("Add Credit Card", UIImage.FromFile(@"Images/ProfileView/ic_card.png")); topTextRowView.AddIfNotNull(firstNameTextField, lastNameTextField); topTextRowView.AddConstraints( firstNameTextField.AtTopOf(topTextRowView), firstNameTextField.AtLeftOf(topTextRowView), firstNameTextField.WithRelativeWidth(topTextRowView, 0.475f), firstNameTextField.WithSameHeight(topTextRowView), lastNameTextField.AtTopOf(topTextRowView), lastNameTextField.AtRightOf(topTextRowView), lastNameTextField.WithRelativeWidth(topTextRowView, 0.475f), lastNameTextField.WithSameHeight(topTextRowView) ); centerTextRowView.AddIfNotNull(emailTextField, addressTextField, cityTextField); centerTextRowView.AddConstraints( emailTextField.AtTopOf(centerTextRowView), emailTextField.WithSameCenterX(centerTextRowView), emailTextField.WithSameWidth(centerTextRowView), emailTextField.WithRelativeHeight(centerTextRowView, 0.3f), addressTextField.Below(emailTextField, 10), addressTextField.WithSameCenterX(centerTextRowView), addressTextField.WithSameWidth(centerTextRowView), addressTextField.WithRelativeHeight(centerTextRowView, 0.3f), cityTextField.Below(addressTextField, 10), cityTextField.WithSameCenterX(centerTextRowView), cityTextField.WithSameWidth(centerTextRowView), cityTextField.WithRelativeHeight(centerTextRowView, 0.3f) ); bottomTextRowView.AddIfNotNull(stateTextField, zipCodeTextField); bottomTextRowView.AddConstraints( stateTextField.AtTopOf(bottomTextRowView), stateTextField.AtLeftOf(bottomTextRowView), stateTextField.WithRelativeWidth(bottomTextRowView, 0.475f), stateTextField.WithSameHeight(bottomTextRowView), zipCodeTextField.AtTopOf(bottomTextRowView), zipCodeTextField.AtRightOf(bottomTextRowView), zipCodeTextField.WithRelativeWidth(bottomTextRowView, 0.475f), zipCodeTextField.WithSameHeight(bottomTextRowView) ); bottomView.AddIfNotNull(addLicenseButton, addCreditCardButton); bottomView.AddConstraints( addLicenseButton.AtTopOf(bottomView), addLicenseButton.WithSameCenterX(bottomView), addLicenseButton.WithSameWidth(bottomView), addLicenseButton.WithRelativeHeight(bottomView, 0.4f), addCreditCardButton.Below(addLicenseButton, 10), addCreditCardButton.WithSameCenterX(bottomView), addCreditCardButton.WithSameWidth(bottomView), addCreditCardButton.WithRelativeHeight(bottomView, 0.4f) ); scrollView.AddIfNotNull(topTextRowView, centerTextRowView, bottomTextRowView, bottomView); scrollView.AddConstraints( topTextRowView.AtTopOf(scrollView, 30), topTextRowView.WithSameWidth(scrollView), topTextRowView.WithSameCenterX(scrollView), topTextRowView.WithRelativeHeight(scrollView, 0.12f), centerTextRowView.Below(topTextRowView, 10), centerTextRowView.WithSameWidth(scrollView), centerTextRowView.AtLeftOf(scrollView), centerTextRowView.AtRightOf(scrollView), centerTextRowView.WithRelativeHeight(scrollView, 0.4f), bottomTextRowView.Below(centerTextRowView, 10), bottomTextRowView.WithSameWidth(scrollView), bottomTextRowView.WithSameCenterX(scrollView), bottomTextRowView.WithRelativeHeight(scrollView, 0.12f), bottomView.Below(bottomTextRowView, 10), bottomView.WithSameWidth(scrollView), bottomView.AtLeftOf(scrollView), bottomView.AtRightOf(scrollView), bottomView.AtBottomOf(scrollView, 100), bottomView.WithRelativeHeight(scrollView, 0.27f) ); View.AddIfNotNull(topView, scrollView); View.AddConstraints( topView.AtTopOf(View), topView.WithSameWidth(View), topView.WithRelativeHeight(View, 0.2f), scrollView.Below(topView, 30), scrollView.AtLeftOf(View, 30), scrollView.AtRightOf(View, 30), scrollView.WithRelativeHeight(View, 0.8f) ); EnableNextKeyForTextFields(firstNameTextField.TextFieldWithValidator.TextField, lastNameTextField.TextFieldWithValidator.TextField, emailTextField.TextFieldWithValidator.TextField, addressTextField.TextFieldWithValidator.TextField, cityTextField.TextFieldWithValidator.TextField, stateTextField.TextFieldWithValidator.TextField, zipCodeTextField.TextFieldWithValidator.TextField); }
public PersonSelectionEdit() : base() { /** * Data */ var content = Content.GameContent.Get; MaleHeads = content.AvatarCollections.Get("ea_male_heads.col"); MaleOutfits = content.AvatarCollections.Get("ea_male.col"); FemaleHeads = content.AvatarCollections.Get("ea_female_heads.col"); FemaleOutfits = content.AvatarCollections.Get("ea_female.col"); /** * UI */ UIScript ui = RenderScript("personselectionedit1024.uis"); Position = new Vector2((GlobalSettings.Default.GraphicsWidth - 1024) / 2, (GlobalSettings.Default.GraphicsHeight - 768) / 2) * FSOEnvironment.DPIScaleFactor; m_ExitButton = (UIButton)ui["ExitButton"]; m_ExitButton.OnButtonClick += new ButtonClickDelegate(m_ExitButton_OnButtonClick); CancelButton = (UIButton)ui["CancelButton"]; CancelButton.OnButtonClick += new ButtonClickDelegate(CancelButton_OnButtonClick); //CancelButton.Disabled = true; DescriptionTextEdit.CurrentText = ui.GetString("DefaultAvatarDescription"); DescriptionSlider.AttachButtons(DescriptionScrollUpButton, DescriptionScrollDownButton, 1); DescriptionTextEdit.AttachSlider(DescriptionSlider); DescriptionTextEdit.CurrentText = DefaultAvatarDescription; DescriptionTextEdit.OnChange += DescriptionTextEdit_OnChange; NameTextEdit.OnChange += new ChangeDelegate(NameTextEdit_OnChange); NameTextEdit.CurrentText = GlobalSettings.Default.LastUser; AcceptButton.Disabled = NameTextEdit.CurrentText.Length == 0; AcceptButton.OnButtonClick += new ButtonClickDelegate(AcceptButton_OnButtonClick); /** Appearance **/ SkinLightButton.OnButtonClick += new ButtonClickDelegate(SkinButton_OnButtonClick); SkinMediumButton.OnButtonClick += new ButtonClickDelegate(SkinButton_OnButtonClick); SkinDarkButton.OnButtonClick += new ButtonClickDelegate(SkinButton_OnButtonClick); SelectedAppearanceButton = SkinLightButton; m_HeadSkinBrowser = ui.Create <UICollectionViewer>("HeadSkinBrowser"); m_HeadSkinBrowser.OnChange += new ChangeDelegate(HeadSkinBrowser_OnChange); m_HeadSkinBrowser.Init(); Add(m_HeadSkinBrowser); m_BodySkinBrowser = ui.Create <UICollectionViewer>("BodySkinBrowser"); m_BodySkinBrowser.OnChange += new ChangeDelegate(BodySkinBrowser_OnChange); m_BodySkinBrowser.Init(); Add(m_BodySkinBrowser); FemaleButton.OnButtonClick += new ButtonClickDelegate(GenderButton_OnButtonClick); MaleButton.OnButtonClick += new ButtonClickDelegate(GenderButton_OnButtonClick); /** Backgrounds **/ var bg = new UIImage(BackgroundImage).With9Slice(128, 128, 84, 84); AddAt(0, bg); bg.SetSize(GlobalSettings.Default.GraphicsWidth, GlobalSettings.Default.GraphicsHeight); bg.Position = new Vector2((GlobalSettings.Default.GraphicsWidth - 1024) / -2, (GlobalSettings.Default.GraphicsHeight - 768) / -2); Background = bg; var offset = new Vector2(0, 0); if (BackgroundImageDialog != null) { offset = new Vector2(112, 84); AddAt(1, new UIImage(BackgroundImageDialog) { X = 112, Y = 84 }); } /** * Music */ HIT.HITVM.Get.PlaySoundEvent(UIMusic.CAS); SimBox = new UISim { Position = new Vector2(offset.X + 70, offset.Y + 88), Size = new Vector2(140, 200), AutoRotate = true }; Add(SimBox); /** * Init state */ if (GlobalSettings.Default.DebugGender) { Gender = Gender.Male; MaleButton.Selected = true; FemaleButton.Selected = false; } else { Gender = Gender.Female; MaleButton.Selected = false; FemaleButton.Selected = true; } AppearanceType = (AppearanceType)GlobalSettings.Default.DebugSkin; SkinLightButton.Selected = false; SkinMediumButton.Selected = false; SkinDarkButton.Selected = false; switch (AppearanceType) { case AppearanceType.Light: SkinLightButton.Selected = true; break; case AppearanceType.Medium: SkinMediumButton.Selected = true; break; case AppearanceType.Dark: SkinDarkButton.Selected = true; break; } RefreshCollections(); SearchCollectionForInitID(GlobalSettings.Default.DebugHead, GlobalSettings.Default.DebugBody); FSO.UI.Model.DiscordRpcEngine.SendFSOPresence("In Create A Sim"); GameThread.NextUpdate(x => { FSOFacade.Hints.TriggerHint("screen:cas"); }); }
public static String[] CalculatePValue(UIImage image, ref nfloat totP, ref nfloat avgP) { UIImage uiImagePic = image; CIContext ctx = CIContext.FromOptions(null); CGImage cgimage = uiImagePic.CGImage; nfloat powerValueAvg = 0.0f; nfloat powerValueTot = 0.0f; nint numPixels = 0; //compute values nint width = cgimage.Width; nint height = cgimage.Height; nint bpr = cgimage.BytesPerRow; nint bpp = cgimage.BitsPerPixel; nint bpc = cgimage.BitsPerComponent; nint bytes_per_pixel = bpp / bpc; CGBitmapFlags info = cgimage.BitmapInfo; CGDataProvider provider = cgimage.DataProvider; NSData data = provider.CopyData(); IntPtr bytesintp = data.Bytes; byte[] bytes = new byte[data.Length]; Marshal.Copy(bytesintp, bytes, 0, (int)data.Length); Console.WriteLine("Pixel Data:"); for (nint row = 0; row < height; row++) { for (nint col = 0; col < width; col++) { byte[] pixel = new byte[bytes_per_pixel]; for (int i = 0; i < bytes_per_pixel; i++) { pixel [i] = bytes [row * bpr + col * bytes_per_pixel + i]; } //Console.Write("("); for (nint x = 0; x < bytes_per_pixel; x++) { //pixel[0] is r //pixel[1] is g //pixel[2] is b //pixel[3] is alpha numPixels++; nfloat curPower = pixel [0] * 0.299f + pixel [1] * 0.587f + pixel [2] * 0.0722f; powerValueTot += curPower; powerValueAvg = powerValueTot / numPixels; // Console.Write(pixel[x]); // if( x < bytes_per_pixel - 1 ) // Console.Write(","); } //Console.Write(")"); //if( col < width - 1 ) // Console.Write(", "); } //Console.Write("\n"); } totP = powerValueTot; avgP = powerValueAvg; string outputToName; outputToName = powerValueAvg.ToString("0.0000"); string outputToName2 = powerValueTot.ToString("0.0000"); string[] strToRet = new string[2]; strToRet [0] = outputToName; strToRet [1] = outputToName2; return(strToRet); }
void getRotatorItem() { SFRotatorItem item1 = new SFRotatorItem(); UIView view1 = new UIView(); UIImageView image1 = new UIImageView(); image1.Frame = view1.Frame; image1.Image = UIImage.FromFile("movie1.png"); item1.View = view1; view1.AddSubview(image1); SFRotatorItem item2 = new SFRotatorItem(); UIView view2 = new UIView(); UIImageView image2 = new UIImageView(); image2.Frame = view2.Frame; image2.Image = UIImage.FromFile("movie2.png"); item2.View = view2; view2.AddSubview(image2); SFRotatorItem item3 = new SFRotatorItem(); UIView view3 = new UIView(); UIImageView image3 = new UIImageView(); image3.Frame = view3.Frame; image3.Image = UIImage.FromFile("movie3.png"); item3.View = view3; view3.AddSubview(image3); SFRotatorItem item4 = new SFRotatorItem(); UIView view4 = new UIView(); UIImageView image4 = new UIImageView(); image4.Frame = view4.Frame; image4.Image = UIImage.FromFile("movie4.png"); item4.View = view4; view4.AddSubview(image4); SFRotatorItem item5 = new SFRotatorItem(); UIView view5 = new UIView(); UIImageView image5 = new UIImageView(); image5.Frame = view5.Frame; image5.Image = UIImage.FromFile("movie5.png"); item5.View = view5; view5.AddSubview(image5); SFRotatorItem item6 = new SFRotatorItem(); UIView view6 = new UIView(); UIImageView image6 = new UIImageView(); image6.Frame = view6.Frame; image6.Image = UIImage.FromFile("movie6.png"); item6.View = view6; view6.AddSubview(image6); SFRotatorItem item7 = new SFRotatorItem(); UIView view7 = new UIView(); UIImageView image7 = new UIImageView(); image7.Frame = view7.Frame; image7.Image = UIImage.FromFile("movie7.png"); item7.View = view7; view7.AddSubview(image7); image1.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image2.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image3.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image4.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image5.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image6.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image7.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; array.Add(item1); array.Add(item2); array.Add(item3); array.Add(item4); array.Add(item5); }
public void Initialize() { if (init) { return; } init = true; X = C.X_MID - 128; Y = 64; Frame = new CGRect(X, Y, 256, C.Y_MAX - 128); BackgroundColor = UIColor.Gray; Layer.BorderWidth = 3; Layer.BorderColor = UIColor.White.CGColor; AvatarView = new UIButton(); AvatarView.Frame = new CGRect(8, 32, 64, 64); AvatarView.SetImage(ViewController.Client.Image, UIControlState.Normal); AvatarView.AddTarget(ViewController.BtnHandler, new Selector("SelectAvatar"), UIControlEvent.TouchUpInside); AvatarView.ContentMode = UIViewContentMode.ScaleAspectFit; Title = new UITextView(); Title.Frame = new CGRect(64, 0, 128, 64); Title.BackgroundColor = UIColor.Clear; Title.Text = "Settings"; Title.Font = Fonts.Settings_Title; Title.TextAlignment = UITextAlignment.Center; Header = new UIView(); Header.BackgroundColor = UIColor.Red; Header.Frame = new CGRect(0, 0, Frame.Width, 32); TypeView = new UIToggle("Option1", "Option2"); TypeView.Frame = new CGRect(0, Frame.Width - 138, 240, 128); TypeView.Initialize(); TypeView.SetImages(new UIImage[] { UIImage.FromBundle("settings_0"), UIImage.FromBundle("settings_1") }); JoinClassView = new UIButton(); JoinClassView.Frame = new CGRect(0, Frame.Height - 186, 240, 128); JoinClassView.SetImage(UIImage.FromBundle("button_joinroom"), UIControlState.Normal); JoinClassView.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; JoinClassView.AddTarget(this, new Selector("ShowJoinRoom"), UIControlEvent.TouchUpInside); Username = new UITextView(); Username.Text = ViewController.Client.Username; Username.Frame = new CGRect(80, 24, 128, 32); Username.BackgroundColor = UIColor.Clear; Username.Font = Fonts.Medium; Bio = new UITextView(); Bio.Text = ViewController.Client.Bio; Bio.Frame = new CGRect(48, 48, 192, 64); Bio.BackgroundColor = UIColor.Clear; Bio.Font = Fonts.Small; Bio.TextAlignment = UITextAlignment.Center; Cancel = new UIButton(); Cancel.Frame = new CGRect(Frame.Width - 32, 0, 32, 32); Cancel.SetImage(UIImage.FromBundle("button_cancel"), UIControlState.Normal); Cancel.ContentMode = UIViewContentMode.ScaleAspectFit; Cancel.AddTarget(this, new Selector("Cancel"), UIControlEvent.TouchUpInside); }
static int sizer(UIImage img) { var cg = img.CGImage; return(cg.BytesPerRow * cg.Height); }
public override void OnViewModelLoadedOverride() { // [viewTextContainer] // [viewButtons] var safeView = BareUISafeView.CreateAndAddTo(View); { var viewTopSpacer = new UIView() { TranslatesAutoresizingMaskIntoConstraints = false }; safeView.Add(viewTopSpacer); viewTopSpacer.StretchWidth(safeView); var viewTextContainer = new UIStackView() { TranslatesAutoresizingMaskIntoConstraints = false, Axis = UILayoutConstraintAxis.Vertical, Spacing = 8 }; { var labelTitle = new UILabel() { TranslatesAutoresizingMaskIntoConstraints = false, Text = "Power Planner", TextColor = new UIColor(1, 1), Font = UIFont.PreferredTitle1, TextAlignment = UITextAlignment.Center }; viewTextContainer.AddArrangedSubview(labelTitle); labelTitle.StretchWidth(viewTextContainer); var labelSubtitle = new UILabel() { TranslatesAutoresizingMaskIntoConstraints = false, Text = "The ultimate homework planner", TextColor = new UIColor(0.9f, 1), Font = UIFont.PreferredCaption1, TextAlignment = UITextAlignment.Center }; viewTextContainer.AddArrangedSubview(labelSubtitle); labelSubtitle.StretchWidth(viewTextContainer); } safeView.Add(viewTextContainer); viewTextContainer.StretchWidth(safeView, left: 16, right: 16); var viewLowerSpacer = new UIView() { TranslatesAutoresizingMaskIntoConstraints = false }; safeView.Add(viewLowerSpacer); viewLowerSpacer.StretchWidth(safeView); var viewButtons = new UIView() { TranslatesAutoresizingMaskIntoConstraints = false }; { var buttonLogin = PowerPlannerUIHelper.CreatePowerPlannerBlueButton("Log In"); buttonLogin.TranslatesAutoresizingMaskIntoConstraints = false; buttonLogin.TouchUpInside += new WeakEventHandler <EventArgs>(delegate { ViewModel.Login(); }).Handler; viewButtons.Add(buttonLogin); buttonLogin.StretchHeight(viewButtons); var buttonCreateAccount = PowerPlannerUIHelper.CreatePowerPlannerBlueButton("Create Account"); buttonCreateAccount.TranslatesAutoresizingMaskIntoConstraints = false; buttonCreateAccount.TouchUpInside += new WeakEventHandler <EventArgs>(delegate { ViewModel.CreateAccount(); }).Handler; viewButtons.Add(buttonCreateAccount); buttonCreateAccount.StretchHeight(viewButtons); viewButtons.AddConstraints(NSLayoutConstraint.FromVisualFormat($"H:|[buttonLogin(==buttonCreateAccount)]-8-[buttonCreateAccount]|", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, new NSDictionary( "buttonLogin", buttonLogin, "buttonCreateAccount", buttonCreateAccount))); } safeView.Add(viewButtons); viewButtons.StretchWidth(safeView, left: 16, right: 16); safeView.AddConstraints(NSLayoutConstraint.FromVisualFormat($"V:|-16-[viewTopSpacer(==viewLowerSpacer)][viewTextContainer][viewLowerSpacer]-16-[viewButtons]-16-|", NSLayoutFormatOptions.AlignAllCenterX, null, new NSDictionary( "viewTextContainer", viewTextContainer, "viewButtons", viewButtons, "viewTopSpacer", viewTopSpacer, "viewLowerSpacer", viewLowerSpacer))); var buttonSettings = new UIControl() { TranslatesAutoresizingMaskIntoConstraints = false }; { var settingsImage = new UIImageView(UIImage.FromBundle("TabSettings").ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)) { TranslatesAutoresizingMaskIntoConstraints = false, TintColor = UIColor.White, ContentMode = UIViewContentMode.ScaleAspectFit }; buttonSettings.Add(settingsImage); settingsImage.StretchHeight(buttonSettings, top: 4, bottom: 4); var label = new UILabel() { TranslatesAutoresizingMaskIntoConstraints = false, Font = UIFont.PreferredCaption1, TextColor = UIColor.White, Text = "About" }; buttonSettings.Add(label); label.StretchHeight(buttonSettings); buttonSettings.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[image(22)]-8-[label]|", NSLayoutFormatOptions.DirectionLeadingToTrailing, "image", settingsImage, "label", label)); } safeView.Add(buttonSettings); buttonSettings.TouchUpInside += new WeakEventHandler(delegate { OpenAboutPageAsPopup(); }).Handler; buttonSettings.PinToTop(safeView, top: UIDevice.CurrentDevice.CheckSystemVersion(11, 0) ? 12 : 28); // We do this comparison since on iOS 11 the safe view adds extra padding buttonSettings.PinToLeft(safeView, left: 12); buttonSettings.SetHeight(30); } base.OnViewModelLoadedOverride(); }
public override void ViewDidLoad() { base.ViewDidLoad(); ImagePicker = new UIImagePickerController(); NavigationItem.HidesBackButton = true; NavigationItem.Title = ViewModel.User; color.Layer.CornerRadius = 30; color.Layer.MasksToBounds = true; //color.SetTitle(_colorValue, UIControlState.Normal); var set = this.CreateBindingSet <MakeupView, MakeupViewModel>(); set.Bind(imageView).For(t => t.Image).To(vm => vm.ImageBytes).WithConversion("InMemoryImage"); //set.Bind(password).For(t => t.Text).To(vm => vm.UserPassword); //set.Bind(login).For(b => b.KeyCommands).To(vm => vm.User) //set.Bind(library).To("BrowseLibrary"); set.Apply(); camera.TouchUpInside += (sender, e) => { if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) { /*ImagePicker = new UIImagePickerController(); * ImagePicker.Delegate = Self; * ImagePicker.SourceType = UIImagePickerControllerSourceType.Camera; * ImagePicker.AllowsEditing = true; * this.PresentViewController(ImagePicker, true, null); * } */ var task = Mvx.Resolve <IMvxPictureChooserTask>(); task.TakePicture(500, 90, stream => { var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); ViewModel.ImageBytes = memoryStream.ToArray(); }, () => { }); } }; library.TouchUpInside += (sender, e) => { if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) { var task = Mvx.Resolve <IMvxPictureChooserTask>(); task.ChoosePictureFromLibrary(500, 90, stream => { var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); ViewModel.ImageBytes = memoryStream.ToArray(); var data = NSData.FromArray(memoryStream.ToArray()); imageView.Image = UIImage.LoadFromData(data); }, () => { }); } }; filter.TouchUpInside += async(sender, e) => { await ViewModel.GoToFilterCommand.ExecuteAsync(); }; color.TouchUpInside += async(sender, e) => { //this.CreateBinding(_chosenColor).To((MakeupViewModel vm) => vm.ColorName).Apply(); await ViewModel.GoToProductCommand.ExecuteAsync(); }; }
// 270 : 16 40 ?? 16 public NPCBrowser(Mod mod) { categories.Clear(); this.npcView = new NPCView(); this.mod = mod; this.CanMove = true; base.Width = this.npcView.Width + this.spacing * 2f; base.Height = 300f; // 272f this.npcView.Position = new Vector2(this.spacing, base.Height - this.npcView.Height - this.spacing * 3f); this.AddChild(this.npcView); this.ParseList2(); Texture2D texture = mod.GetTexture("UI/closeButton"); UIImage uIImage = new UIImage(texture); uIImage.Anchor = AnchorPosition.TopRight; uIImage.Position = new Vector2(base.Width - this.spacing, this.spacing); uIImage.onLeftClick += new EventHandler(this.bClose_onLeftClick); this.AddChild(uIImage); this.textbox = new UITextbox(); this.textbox.Anchor = AnchorPosition.BottomLeft; //this.textbox.Position = new Vector2(base.Width - this.spacing * 2f + uIImage.Width * numWidth * 2, this.spacing /** 2f + uIImage.Height*/); this.textbox.Position = new Vector2(this.spacing, base.Height - this.spacing); this.textbox.KeyPressed += new UITextbox.KeyPressedHandler(this.textbox_KeyPressed); this.AddChild(this.textbox); for (int j = 0; j < NPCBrowser.categoryIcons.Length; j++) { UIImage uIImage2 = new UIImage(NPCBrowser.categoryIcons[j]); Vector2 position = new Vector2(this.spacing, this.spacing); uIImage2.Scale = 32f / Math.Max(categoryIcons[j].Width, categoryIcons[j].Height); position.X += (float)(j % 6 * 40); position.Y += (float)(j / 6 * 40); if (categoryIcons[j].Height > categoryIcons[j].Width) { position.X += (32 - categoryIcons[j].Width) / 2; } else if (categoryIcons[j].Height < categoryIcons[j].Width) { position.Y += (32 - categoryIcons[j].Height) / 2; } uIImage2.Position = position; uIImage2.Tag = j; uIImage2.onLeftClick += new EventHandler(this.button_onLeftClick); uIImage2.ForegroundColor = NPCBrowser.buttonColor; if (j == 0) { uIImage2.ForegroundColor = NPCBrowser.buttonSelectedColor; } uIImage2.Tooltip = NPCBrowser.categNames[j]; NPCBrowser.bCategories[j] = uIImage2; this.AddChild(uIImage2); } npcView.selectedCategory = NPCBrowser.categories[0].ToArray(); npcView.activeSlots = npcView.selectedCategory; npcView.ReorderSlots(); textures = new Texture2D[] { mod.GetTexture("UI/NPCLifeIcon"), mod.GetTexture("UI/NPCDamageIcon"), mod.GetTexture("UI/NPCDefenseIcon"), mod.GetTexture("UI/NPCKnockbackIcon"), }; }
/// <summary> /// Uses values from the custom pin to set up the values of the custom annotation (IOS Pin marker). /// </summary> /// <param name="mapView"></param> /// <param name="annotation"></param> /// <returns></returns> MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) { Console.WriteLine("Number of Custom Pins: " + customPins.Count); MKAnnotationView annotationView = null; Console.WriteLine("Number of Actual Map Pins: " + formsMap.Pins.Count); if (annotation is MKUserLocation) { return(null); } /*TE: The application can crashe becuase of this*/ if (!(annotation is MKPointAnnotation)) { Console.WriteLine("Type wasn't a MKPointAnnotation, skipped"); return(null); } var customPin = GetCustomPin(annotation as MKPointAnnotation); if (customPin == null) { throw new Exception("Custom pin not found"); } annotationView = mapView.DequeueReusableAnnotation(customPin.Id.ToString()); if (annotationView == null) { annotationView = new CustomMKAnnotationView(annotation, customPin.Id.ToString()); annotationView.Image = UIImage.FromFile("MapPin.png"); annotationView.CalloutOffset = new CGPoint(0, 0); annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure); ((CustomMKAnnotationView)annotationView).Id = customPin.Id.ToString(); ((CustomMKAnnotationView)annotationView).Url = customPin.Url; ((CustomMKAnnotationView)annotationView).BuildingName = customPin.BuildingName; ((CustomMKAnnotationView)annotationView).EventTime = customPin.EventTime; ((CustomMKAnnotationView)annotationView).foodFinderEvent = customPin.foodFinderEvent; annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure); ((CustomMKAnnotationView)annotationView).Id = customPin.Id.ToString(); ((CustomMKAnnotationView)annotationView).Url = customPin.Url; ((CustomMKAnnotationView)annotationView).BuildingName = customPin.BuildingName; } /*TE: Disable callout if we adding an event. This code should not stop the IOS stuff from working.*/ if (formsMap.SelectingLocation) { annotationView.CanShowCallout = false; } else { annotationView.CanShowCallout = true; } return(annotationView); }
private void prepare(UIImage image, UIColor tintColor) { this.Image = image; this.TintColor = tintColor; }
static async void LoadPic(string src) { UIImage.LoadSource(await WebClass.Get(src), pic); }
public override void ViewDidLoad() { base.ViewDidLoad(); this.NavigationBar.BarTintColor = UIColor.FromPatternImage(UIImage.FromFile("*****@*****.**")); }
public FirstViewController(IntPtr handle) : base(handle) { this.Title = NSBundle.MainBundle.LocalizedString("First", "First"); this.TabBarItem.Image = UIImage.FromBundle("Images/first"); }
public static UIImage UIImageFromUrl(string uri) { using (var url = new NSUrl(uri)) using (var data = NSData.FromUrl(url)) return(UIImage.LoadFromData(data)); }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { this.Window = new UIWindow(UIScreen.MainScreen.Bounds); // ViewControllers var aRootVC = new DEMOHomeViewController(); var secondVC = new DEMOSecondViewController(); //define the menu structure var sections = new List <REMenuItemSection>() { new REMenuItemSection() { Items = new List <REMenuItem>() { new REMenuViewControllerItem() { //View exisiting view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"home-48"), Title = @"Home", ViewController = aRootVC, }, new REMenuViewControllerItem() { //New view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"about-48"), Title = @"Profile", ViewController = secondVC, }, new REMenuViewControllerItem() { //New view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"about-48"), Title = @"Chats", ViewController = secondVC, }, }, }, new REMenuItemSection() { Title = "Friends Online", Items = new List <REMenuItem>() { new REMenuViewControllerItem() { //View exisiting view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"business_contact-48"), Title = @"John Appleseed", ViewController = secondVC, }, new REMenuViewControllerItem() { //New view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"business_contact-48"), Title = @"John Doe", ViewController = secondVC, }, new REMenuViewControllerItem() { //New view controller, will be reused everytime the item is selected Icon = UIImage.FromBundle(@"business_contact-48"), Title = @"Test User", ViewController = secondVC, }, new REMenuActionItem() { //Action is called, on the UI thread, everytime the item is selected Icon = UIImage.FromBundle(@"ask_question-48"), Title = @"Logout", Command = () => { var uiAlert = new UIAlertView("Logout", "Are you sure you want to log out?", null, "No", "Yes"); uiAlert.Show(); }, }, }, }, }; //build the default navigation controller and menu controller var navigationController = new RENavigationController(aRootVC); var menuController = new REFrostedMenuViewController() { Avatar = UIImage.FromBundle(@"monkey.png"), AvatarName = @"Xamarin Monkey", Sections = sections, }; // Setup the frosted view controller var frostedViewController = new REFrostedViewController.REFrostedViewController(navigationController, menuController) { Direction = REFrostedViewControllerDirection.Left, LiveBlurBackgroundStyle = REFrostedViewControllerLiveBackgroundStyle.Light, LiveBlur = true, Delegate = this, }; this.Window.RootViewController = frostedViewController; this.Window.BackgroundColor = UIColor.White; this.Window.MakeKeyAndVisible(); return(true); }
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell("MyCell") as TripsTableViewCell; var place = ViewModel.Places[indexPath.Row]; cell.Trip = place.Name; cell.DescriptionT = place.Description; cell.ImagePath.Image = UIImage.FromBundle(place.AssetName); cell.Rating.Image = place.Rating > 0 ? UIImage.FromBundle("ThumbUp") : UIImage.FromBundle("ThumbDown"); return(cell); }
private async Task AssignImageAsync() { // reset the scroll or the size and offsets will all be off for the new image (do this before updating the image) ResetScrollView(); var webSource = _zoomImage.Source as UriImageSource; var fileSource = _zoomImage.Source as FileImageSource; var streamSource = _zoomImage.Source as StreamImageSource; if (webSource != null) { try { var url = webSource.Uri.ToString(); using (var data = NSData.FromUrl(NSUrl.FromString(url))) using (var image = UIImage.LoadFromData(data)) { if (_imageView == null) { _imageView = new UIImageView(image); } else { _imageView.Image = image; } } } catch (Exception e) { Console.WriteLine($"Error loading image from {webSource.Uri.ToString()}. Exception: {e.Message}"); _imageView = new UIImageView(); } } else if (fileSource != null) { try { // use a file source using (var image = UIImage.FromFile(fileSource.File)) { if (_imageView == null) { _imageView = new UIImageView(image); } else { _imageView.Image = image; } } } catch (Exception e) { Console.WriteLine($"Error loading image from file {fileSource.File}. Exception: {e.Message}"); _imageView = new UIImageView(); } } else if (streamSource != null) { try { var cts = new CancellationTokenSource(); using (var stream = await streamSource.Stream(cts.Token)) using (var data = NSData.FromStream(stream)) using (var image = UIImage.LoadFromData(data)) { if (_imageView == null) { _imageView = new UIImageView(image); } else { _imageView.Image = image; } } } catch (Exception e) { Console.WriteLine($"Error loading image from stream. Exception: {e.Message}"); _imageView = new UIImageView(); } } else { Debug.WriteLine("ZoomImageRenderer: Unable to load image, creating empty image view."); if (_imageView == null) { _imageView = new UIImageView(); } else { _imageView.Image = null; } } _imageView.SizeToFit(); _scrollView.ContentSize = _imageView.Frame.Size; }
/// <summary> /// Loads the image from given stream asynchronously. /// </summary> /// <returns>An awaitable task.</returns> /// <param name="stream">The stream to get data from.</param> public override async Task <GenerateResult> LoadFromStreamAsync(Stream stream) { if (stream == null) { return(GenerateResult.Failed); } if (IsCancelled) { return(GenerateResult.Canceled); } WithLoadingResult <UIImage> resultWithImage; UIImage image = null; try { resultWithImage = await GetImageAsync("Stream", ImageSource.Stream, false, stream).ConfigureAwait(false); image = resultWithImage.Item; } catch (Exception ex) { Logger.Error("An error occured while retrieving image.", ex); resultWithImage = new WithLoadingResult <UIImage>(LoadingResult.Failed); image = null; } if (image == null) { await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false); return(resultWithImage.GenerateResult); } if (CanUseMemoryCache()) { ImageCache.Instance.Add(GetKey(), resultWithImage.ImageInformation, image); } if (IsCancelled) { return(GenerateResult.Canceled); } if (!_target.IsTaskValid(this)) { return(GenerateResult.InvalidTarget); } try { // Post on main thread await MainThreadDispatcher.PostAsync(() => { if (IsCancelled) { return; } _target.Set(this, image, true, false); Completed = true; Parameters?.OnSuccess(resultWithImage.ImageInformation, resultWithImage.Result); }).ConfigureAwait(false); if (!Completed) { return(GenerateResult.Failed); } } catch (Exception ex2) { await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false); throw ex2; } return(GenerateResult.Success); }
public Swiping() { save = new UIButton(); save.SetTitle("Save", UIControlState.Normal); save.BackgroundColor = UIColor.DarkGray; save.Font = UIFont.FromName("Helvetica-Bold", 12f); save.TouchDown += Save_TouchDown; cancel = new UIButton(); cancel.SetTitle("Cancel", UIControlState.Normal); cancel.TouchDown += Cancel_TouchDown; cancel.BackgroundColor = UIColor.DarkGray; cancel.Font = UIFont.FromName("Helvetica-Bold", 12f); col1 = new UILabel(); col1.Text = "Order ID"; col2 = new UILabel(); col2.Text = "Customer ID"; col3 = new UILabel(); col3.Text = "Employee ID"; col4 = new UILabel(); col4.Text = "Name"; orderIDText = new UITextField(); orderIDText.AllowsEditingTextAttributes = true; orderIDText.ShouldReturn += (textField) => { orderIDText.ResignFirstResponder(); return(true); }; customerIDText = new UITextField(); customerIDText.ShouldReturn += (textField) => { customerIDText.ResignFirstResponder(); return(true); }; employeeIDText = new UITextField(); employeeIDText.ShouldReturn += (textField) => { employeeIDText.ResignFirstResponder(); return(true); }; nameText = new UITextField(); nameText.ShouldReturn += (textField) => { nameText.ResignFirstResponder(); return(true); }; orderIDText.Hidden = true; customerIDText.Hidden = true; employeeIDText.Hidden = true; nameText.Hidden = true; col1.Hidden = true; col2.Hidden = true; col3.Hidden = true; col4.Hidden = true; save.Hidden = true; cancel.Hidden = true; this.detailView = new DetailView(); this.detailView.Hidden = true; this.SfGrid = new SfDataGrid(); this.viewModel = new SwipingViewModel(); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.ColumnSizer = ColumnSizer.Star; UIButton leftSwipeViewText = new UIButton(); leftSwipeViewText.SetTitle("Edit", UIControlState.Normal); leftSwipeViewText.SetTitleColor(UIColor.White, UIControlState.Normal); leftSwipeViewText.VerticalAlignment = UIControlContentVerticalAlignment.Center; leftSwipeViewText.BackgroundColor = UIColor.FromRGB(0, 158, 218); leftSwipeViewText.TouchUpInside += LeftSwipeViewButton_TouchUpInside; leftSwipeViewText.Frame = new CGRect(56, 0, 60, 45); UIButton leftSwipeViewButton = new UIButton(); leftSwipeViewButton.SetImage(UIImage.FromFile("Images/Edit.png"), UIControlState.Normal); leftSwipeViewButton.BackgroundColor = UIColor.FromRGB(0, 158, 218); leftSwipeViewButton.TouchUpInside += LeftSwipeViewButton_TouchUpInside; leftSwipeViewButton.Frame = new CGRect(16, 10, 24, 24); CustomSwipeView leftSwipeView = new CustomSwipeView(); leftSwipeView.AddSubview(leftSwipeViewButton); leftSwipeView.AddSubview(leftSwipeViewText); leftSwipeView.Frame = new CGRect(0, 0, 120, 44); leftSwipeView.BackgroundColor = UIColor.FromRGB(0, 158, 218); UIButton rightSwipeViewText = new UIButton(); rightSwipeViewText.SetTitle("Delete", UIControlState.Normal); rightSwipeViewText.SetTitleColor(UIColor.White, UIControlState.Normal); rightSwipeViewText.VerticalAlignment = UIControlContentVerticalAlignment.Center; rightSwipeViewText.BackgroundColor = UIColor.FromRGB(220, 89, 95); rightSwipeViewText.TouchUpInside += RightSwipeViewButton_TouchUpInside; rightSwipeViewText.Frame = new CGRect(56, 0, 60, 45); UIButton rightSwipeViewButton = new UIButton(); rightSwipeViewButton.SetImage(UIImage.FromFile("Images/Delete.png"), UIControlState.Normal); rightSwipeViewButton.BackgroundColor = UIColor.FromRGB(220, 89, 95); rightSwipeViewButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; rightSwipeViewButton.TouchUpInside += RightSwipeViewButton_TouchUpInside; rightSwipeViewButton.Frame = new CGRect(16, 10, 24, 24); CustomSwipeView rightSwipeView = new CustomSwipeView(); rightSwipeView.AddSubview(rightSwipeViewButton); rightSwipeView.AddSubview(rightSwipeViewText); rightSwipeView.Frame = new CGRect(0, 0, 120, 44); rightSwipeView.BackgroundColor = UIColor.FromRGB(220, 89, 95); this.SfGrid.AllowSwiping = true; this.SfGrid.LeftSwipeView = leftSwipeView; this.SfGrid.RightSwipeView = rightSwipeView; this.SfGrid.SwipeEnded += SfGrid_SwipeEnded; this.SfGrid.SwipeStarted += SfGrid_SwipeStarted; this.SfGrid.GridTapped += SfGrid_GridTapped; this.SfGrid.GridLongPressed += SfGrid_GridLongPressed; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; this.SfGrid.Columns.Add(OrderID); this.SfGrid.Columns.Add(CustomerID); this.SfGrid.Columns.Add(EmployeeID); this.SfGrid.Columns.Add(Name); this.AddSubview(SfGrid); this.AddSubview(detailView); this.AddSubview(col1); this.AddSubview(col2); this.AddSubview(col3); this.AddSubview(col4); this.AddSubview(orderIDText); this.AddSubview(customerIDText); this.AddSubview(employeeIDText); this.AddSubview(nameText); this.AddSubview(save); this.AddSubview(cancel); }
protected virtual async Task <WithLoadingResult <UIImage> > GetImageAsync(string sourcePath, ImageSource source, bool isPlaceholder, Stream originalStream = null) { if (IsCancelled) { return(new WithLoadingResult <UIImage>(LoadingResult.Canceled)); } LoadingResult?result = null; UIImage image = null; byte[] bytes = null; string path = sourcePath; ImageInformation imageInformation = null; try { if (originalStream != null) { try { // check is stream is memorystream var ms = originalStream as MemoryStream; if (ms != null) { bytes = ms.ToArray(); } else if (originalStream.CanSeek) { bytes = new byte[originalStream.Length]; await originalStream.ReadAsync(bytes, 0, (int)originalStream.Length, CancellationToken.Token).ConfigureAwait(false); } else { using (var ms2 = new MemoryStream()) { await originalStream.CopyToAsync(ms2).ConfigureAwait(false); bytes = ms2.ToArray(); } } path = sourcePath; result = LoadingResult.Stream; } finally { originalStream.Dispose(); } } else { using (var resolver = DataResolverFactory.GetResolver(source, Parameters, DownloadCache, MainThreadDispatcher)) { var data = await resolver.GetData(path, CancellationToken.Token).ConfigureAwait(false); if (data == null) { return(new WithLoadingResult <UIImage>(LoadingResult.Failed)); } image = data.Image; bytes = data.Data; path = data.ResultIdentifier; result = data.Result; imageInformation = data.ImageInformation; } } } catch (OperationCanceledException) { Logger.Debug(string.Format("Image request for {0} got cancelled.", path)); return(new WithLoadingResult <UIImage>(LoadingResult.Canceled)); } catch (Exception ex) { var message = String.Format("Unable to retrieve image data from source: {0}", sourcePath); Logger.Error(message, ex); Parameters?.OnError(ex); return(new WithLoadingResult <UIImage>(LoadingResult.Failed)); } if (bytes == null && image == null) { if (result != null && (int)result < 0) // it's below zero if it's an error { return(new WithLoadingResult <UIImage>(result.Value)); } else { return(new WithLoadingResult <UIImage>(LoadingResult.Failed)); } } if (IsCancelled) { return(new WithLoadingResult <UIImage>(LoadingResult.Canceled)); } UIImage imageIn = image; NSData nsdata = null; if (imageIn == null) { // Special case to handle WebP decoding on iOS if (sourcePath.ToLowerInvariant().EndsWith(".webp", StringComparison.InvariantCulture)) { imageIn = new WebP.Touch.WebPCodec().Decode(bytes); } else { // nfloat scale = _imageScale >= 1 ? _imageScale : ScaleHelper.Scale; nsdata = NSData.FromArray(bytes); if (nsdata == null) { return(new WithLoadingResult <UIImage>(LoadingResult.Failed)); } } } bytes = null; // Setting image informations if (imageInformation == null) { imageInformation = new ImageInformation(); } imageInformation.SetKey(path == "Stream" ? GetKey() : GetKey(sourcePath), Parameters.CustomCacheKey); // We rely on ImageIO for all datasources except AssetCatalog, this way we don't generate temporary UIImage // furthermore we can do all the work in a thread safe way and in threadpool if (nsdata != null) { int downsampleWidth = Parameters.DownSampleSize?.Item1 ?? 0; int downsampleHeight = Parameters.DownSampleSize?.Item2 ?? 0; if (Parameters.DownSampleUseDipUnits) { downsampleWidth = downsampleWidth.PointsToPixels(); downsampleHeight = downsampleHeight.PointsToPixels(); } imageIn = nsdata.ToImage(new CoreGraphics.CGSize(downsampleWidth, downsampleHeight), ScaleHelper.Scale, NSDataExtensions.RCTResizeMode.ScaleAspectFill, imageInformation); } else if (Parameters.DownSampleSize != null && imageIn != null) { // if we already have the UIImage in memory it doesn't really matter to resize it // furthermore this will only happen for AssetCatalog images (yet) } bool transformPlaceholdersEnabled = Parameters.TransformPlaceholdersEnabled.HasValue ? Parameters.TransformPlaceholdersEnabled.Value : ImageService.Instance.Config.TransformPlaceholders; if (Parameters.Transformations != null && Parameters.Transformations.Count > 0 && (!isPlaceholder || (isPlaceholder && transformPlaceholdersEnabled))) { var transformations = Parameters.Transformations.ToList(); await _decodingLock.WaitAsync().ConfigureAwait(false); // Applying transformations is both CPU and memory intensive try { if (IsCancelled) { return(new WithLoadingResult <UIImage>(LoadingResult.Canceled)); } foreach (var transformation in transformations) { if (IsCancelled) { return(new WithLoadingResult <UIImage>(LoadingResult.Canceled)); } try { var old = imageIn; var bitmapHolder = transformation.Transform(new BitmapHolder(imageIn)); imageIn = bitmapHolder.ToNative(); // Transformation succeeded, so garbage the source if (old != null && old != imageIn && old.Handle != imageIn.Handle) { old.Dispose(); } } catch (Exception ex) { Logger.Error("Can't apply transformation " + transformation.Key + " to image " + path, ex); } } } finally { _decodingLock.Release(); } } return(WithLoadingResult.Encapsulate(imageIn, result.Value, imageInformation)); }
/// <summary> /// Runs the image loading task: gets image from file, url, asset or cache. Then assign it to the imageView. /// </summary> protected override async Task <GenerateResult> TryGeneratingImageAsync() { WithLoadingResult <UIImage> imageWithResult; UIImage image = null; try { imageWithResult = await RetrieveImageAsync(Parameters.Path, Parameters.Source, false).ConfigureAwait(false); image = imageWithResult.Item; } catch (Exception ex) { Logger.Error("An error occured while retrieving image.", ex); imageWithResult = new WithLoadingResult <UIImage>(LoadingResult.Failed); image = null; } if (image == null) { await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, true).ConfigureAwait(false); return(imageWithResult.GenerateResult); } if (IsCancelled) { return(GenerateResult.Canceled); } if (!_target.IsTaskValid(this)) { return(GenerateResult.InvalidTarget); } try { // Post on main thread await MainThreadDispatcher.PostAsync(() => { if (IsCancelled) { return; } _target.Set(this, image, imageWithResult.Result.IsLocalOrCachedResult(), false); Completed = true; Parameters?.OnSuccess(imageWithResult.ImageInformation, imageWithResult.Result); }).ConfigureAwait(false); if (!Completed) { return(GenerateResult.Failed); } } catch (Exception ex2) { await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false); throw ex2; } return(GenerateResult.Success); }
public Size GetSize(string fileName) { UIImage image = UIImage.FromFile(fileName); return(new Size((double)image.Size.Width, (double)image.Size.Height)); }
public LoginView(string xamarinAccountEmail) { BackgroundColor = UIColor.White; Add(GravatarView = new UIImageView(new RectangleF(PointF.Empty, GravatarSize)) { TranslatesAutoresizingMaskIntoConstraints = false, Image = UIImage.FromBundle("user-default-avatar"), }); GravatarView.Layer.CornerRadius = GravatarSize.Width / 2; GravatarView.Layer.MasksToBounds = true; DisplayGravatar(xamarinAccountEmail); AddConstraint(NSLayoutConstraint.Create( GravatarView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1f, 90f )); AddConstraint(NSLayoutConstraint.Create( GravatarView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, this, NSLayoutAttribute.CenterX, 1f, 0 )); AddConstantSizeConstraints(GravatarView, GravatarSize); Add(EmailField = new UITextField(new RectangleF(10, 10, 300, 30)) { BorderStyle = UITextBorderStyle.RoundedRect, Text = xamarinAccountEmail, TranslatesAutoresizingMaskIntoConstraints = false, Delegate = new EmailFieldDelegate() }); AddConstraint(NSLayoutConstraint.Create( EmailField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, GravatarView, NSLayoutAttribute.Bottom, 1f, 30f )); AddConstraint(NSLayoutConstraint.Create( EmailField, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, GravatarView, NSLayoutAttribute.CenterX, 1f, 0 )); var textSize = new NSString("hello").StringSize(UIFont.SystemFontOfSize(12f)); AddConstantSizeConstraints(EmailField, new SizeF(260, textSize.Height + 16)); Add(PasswordField = new UITextField(new RectangleF(10, 10, 300, 30)) { BorderStyle = UITextBorderStyle.RoundedRect, SecureTextEntry = true, TranslatesAutoresizingMaskIntoConstraints = false, ReturnKeyType = UIReturnKeyType.Go, Placeholder = "Password" }); AddConstraint(NSLayoutConstraint.Create( PasswordField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, EmailField, NSLayoutAttribute.Bottom, 1f, 10f )); AddConstraint(NSLayoutConstraint.Create( PasswordField, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, EmailField, NSLayoutAttribute.CenterX, 1f, 0 )); AddConstantSizeConstraints(PasswordField, new SizeF(260, textSize.Height + 16)); PasswordField.ShouldReturn = field => { field.ResignFirstResponder(); UserDidLogin(this); return(true); }; PasswordField.BecomeFirstResponder(); }