private static NSDictionary GetProxyDictionary(WebProxy webProxy)
        {
            var host   = webProxy.Address.Host;
            var port   = webProxy.Address.Port;
            var values = new []
            {
                NSObject.FromObject(host),
                NSNumber.FromInt32(port),
                NSNumber.FromInt32(1),
                NSObject.FromObject(host),
                NSNumber.FromInt32(port),
                NSNumber.FromInt32(1)
            };
            var keys = new []
            {
                NSObject.FromObject("HTTPProxy"),
                NSObject.FromObject("HTTPPort"),
                NSObject.FromObject("HTTPEnable"),
                NSObject.FromObject("HTTPSProxy"),
                NSObject.FromObject("HTTPSPort"),
                NSObject.FromObject("HTTPSEnable")
            };
            var proxyDictionary = NSDictionary.FromObjectsAndKeys(values, keys);

            return(proxyDictionary);
        }
        public void queryiTunesLibraryForMediaItems(List <LibraryItem> libraryItems)
        {
#if ENABLE_ITUNES_ITEMS
            try
            {
                var mq        = new MPMediaQuery();
                var value     = NSNumber.FromInt32((int)MPMediaType.TypeAnyVideo);
                var predicate = MPMediaPropertyPredicate.PredicateWithValue(value, MPMediaItem.MediaTypeProperty);
                mq.AddFilterPredicate(predicate);

                List <MPMediaItem> mediaItems = new List <MPMediaItem>(mq.Items);
                foreach (MPMediaItem mediaItem in mediaItems)
                {
                    AVAsset asset = AVAsset.FromUrl(mediaItem.AssetURL);
                    if ((asset != null) && isRecording(asset))
                    {
                        LibraryItem libraryItem = new LibraryItem();
                        libraryItem.Storage       = LibraryItemStorage.iTunes;
                        libraryItem.ID            = mediaItem.PersistentID.ToString();
                        libraryItem.LocalFilePath = mediaItem.AssetURL.ToString();
                        fetchMetadata(asset, ref libraryItem);

                        libraryItems.Add(libraryItem);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("ERROR: LocalLibrary.queryiTunesLibraryForMediaItems: " + ex);
            }
#endif
        }
        private void SetGoogleMapControl()
        {
            var mapView = new MapView
            {
                Camera       = CameraPosition.FromCamera(MapTile.MinskLat, MapTile.MinskLong, 11.9f),
                TappedMarker = TappedMarker,
                Settings     =
                {
                    CompassButton = true
                }
            };

            mapView.CameraPositionIdle   += Map_CameraPositionIdle;
            mapView.CoordinateTapped     += Map_CoordinateTapped;
            mapView.PoiWithPlaceIdTapped += Map_PoiWithPlaceIdTapped;
            mapView.WillMove             += Map_WillMove;

            var buckets       = new[] { NSNumber.FromInt32(int.MaxValue) };
            var images        = new[] { UIImage.FromBundle("ic_cluster.png") };
            var iconGenerator = new GMUDefaultClusterIconGenerator(buckets, images);
            var algorithm     = new GMUNonHierarchicalDistanceBasedAlgorithm();
            var renderer      = new ClusterRenderer(mapView, iconGenerator);

            ClusterManager = new GMUClusterManager(mapView, algorithm, renderer);

            SetNativeControl(mapView);
        }
示例#4
0
        public void Bind(Product data)
        {
            _data                  = data;
            _titleLabel.Text       = data.Name.ToUpper();
            _descriptionLabel.Text = (data.Reviews?.FirstOrDefault(x => x.ReviewType == "QuickReview")?.Content) ?? data.Reviews?.FirstOrDefault()?.Content;
            var listPrice = data.Price?.FormattedListPrice;

            if (!string.IsNullOrEmpty(listPrice))
            {
                var attrString = new NSMutableAttributedString(listPrice);
                attrString.AddAttribute(
                    UIStringAttributeKey.StrikethroughStyle,
                    NSNumber.FromInt32((int)NSUnderlineStyle.Single),
                    new NSRange(0, attrString.Length));
                _listPriceLable.AttributedText = attrString;
                _actionsView.BackgroundColor   = Consts.ColorMain.ColorWithAlpha(new nfloat(0.5));
            }
            _salePriceLable.Text = data.Price?.FormattedSalePrice;
            var image = UIImage.FromFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), data.TitleImage));
            var scale = 230 / image.Size.Width;

            image = image.Scale(new CGSize(image.Size.Width * scale, image.Size.Height * scale));
            _productImage.Image = image;
            var imageFrame = _productImage.Frame;

            imageFrame.Size     = image.Size;
            _productImage.Frame = imageFrame;
            _productImage.Image = image;
        }
示例#5
0
        private void SetUnderline(bool underlined)
        {
            try
            {
                var label = (UILabel)Control;
                var text  = (NSMutableAttributedString)label.AttributedText;
                var range = new NSRange(0, text.Length);

                if (underlined)
                {
                    NSRange r;
                    text.GetAttribute(UIStringAttributeKey.UnderlineStyle, 0, out r);

                    text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                }
                else
                {
                    NSRange r;
                    text.GetAttribute(UIStringAttributeKey.UnderlineStyle, 0, out r);

                    text.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, range);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot underline Label. Error: ", ex.Message);
            }
        }
示例#6
0
        void SetupRecorder()
        {
            // An extension is required otherwise the file does not save to a format that browsers support (mp4)
            // Note: output the file rather than the path as the path is calculated via PrivatePath interface in the PCL
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            filename = Path.Combine(documents, DateTimeOffset.Now.ToUnixTimeSeconds().ToString() + ".3gp");

            var audioSession = AVAudioSession.SharedInstance();
            var err          = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

            err = audioSession.SetActive(true);

            NSObject[] values =
            {
                NSNumber.FromFloat(8000.0f),
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.MPEG4AAC),
                NSNumber.FromInt32(1)
            };

            NSObject[] keys =
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey
            };

            recorder = AVAudioRecorder.Create(
                NSUrl.FromFilename(filename),
                new AudioSettings(NSDictionary.FromObjectsAndKeys(values, keys)),
                out var error
                );
        }
 private void SetUnderline(bool underlined)
 {
     try
     {
         var label = (UILabel)Control;
         if (label != null)
         {
             var text = (NSMutableAttributedString)label.AttributedText;
             if (text != null)
             {
                 var range = new NSRange(0, text.Length);
                 if (underlined)
                 {
                     text.AddAttribute(UIStringAttributeKey.StrikethroughStyle,
                                       NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                 }
                 else
                 {
                     text.RemoveAttribute(UIStringAttributeKey.StrikethroughStyle, range);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ex.Track();
     }
 }
示例#8
0
        // Apply your customization here, along w/ exception handling
        protected override void OnAttached()
        {
            try
            {
                // Get an instance of the attached effect
                var effect = (Xamarin101.Effects.LabelUnderlineEffect)Element.Effects.FirstOrDefault(e => e is Xamarin101.Effects.LabelUnderlineEffect);

                if (effect != null)
                {
                    var label = (UILabel)Control;
                    var text  = (NSMutableAttributedString)label.AttributedText;
                    var range = new NSRange(0, text.Length);

                    var passedInLineColor = effect.LineColor;

                    text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                    text.AddAttribute(UIStringAttributeKey.UnderlineColor, passedInLineColor.ToUIColor(), range);
                }
                else
                {
                    Debug.WriteLine("Unable to find a LabelUnderlineEffect.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Unable to set property on attached control. {ex.Message}");
            }
        }
        void UpdateTextDecorations()
        {
            if (!Element.IsSet(Label.TextDecorationsProperty))
                return;

            var textDecorations = Element.TextDecorations;

            var newAttributedText = new NSMutableAttributedString(Control.AttributedText);
            var strikeThroughStyleKey = UIStringAttributeKey.StrikethroughStyle;
            var underlineStyleKey = UIStringAttributeKey.UnderlineStyle;

            var range = new NSRange(0, newAttributedText.Length);

            if ((textDecorations & TextDecorations.Strikethrough) == 0)
                newAttributedText.RemoveAttribute(strikeThroughStyleKey, range);
            else
                newAttributedText.AddAttribute(strikeThroughStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);

            if ((textDecorations & TextDecorations.Underline) == 0)
                newAttributedText.RemoveAttribute(underlineStyleKey, range);
            else
                newAttributedText.AddAttribute(underlineStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                
            Control.AttributedText = newAttributedText;

        }
示例#10
0
        public async Task <IList <Song> > GetAllSongs()
        {
            return(await Task.Run <IList <Song> >(() =>
            {
                IList <Song> songs = new ObservableCollection <Song>();

                MPMediaQuery mq = new MPMediaQuery();
                mq.GroupingType = MPMediaGrouping.Title;
                var value = NSNumber.FromInt32((int)MPMediaType.Music);
                var predicate = MPMediaPropertyPredicate.PredicateWithValue(value, MPMediaItem.MediaTypeProperty);
                mq.AddFilterPredicate(predicate);
                var items = mq.Items;

                foreach (var item in items)
                {
                    if (item != null && !item.IsCloudItem && item.AssetURL != null)
                    {
                        songs.Add(new Song
                        {
                            Id = item.PersistentID,
                            Title = item.Title,
                            Artist = item.Artist,
                            Album = item.AlbumTitle,
                            Genre = item.Genre,
                            Artwork = item.Artwork,
                            Duration = (ulong)item.PlaybackDuration,
                            Uri = item.AssetURL.AbsoluteString
                        });
                    }
                }

                return songs;
            }));
        }
        public void FromObjectsAndKeysGenericTest()
        {
            var keys = new [] {
                new NSString("Key1"),
                new NSString("Key2"),
                new NSString("Key3"),
                new NSString("Key4"),
                new NSString("Key5"),
            };
            var values = new [] {
                NSNumber.FromByte(0x1),
                NSNumber.FromFloat(8.5f),
                NSNumber.FromDouble(10.5),
                NSNumber.FromInt32(42),
                NSNumber.FromBoolean(true),
            };

            var dict = NSMutableDictionary <NSString, NSNumber> .FromObjectsAndKeys(values, keys, values.Length);

            Assert.AreEqual(dict.Count, 5, "count");
            for (int i = 0; i < values.Length; i++)
            {
                Assert.AreEqual(dict [keys [i]], values [i], $"key lookup, Iteration: {i}");
            }
        }
示例#12
0
 public override int ScheduleLocalNotification(string body, int delay)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
     {
         UNUserNotificationCenter     center  = UNUserNotificationCenter.Current;
         UNMutableNotificationContent content = new UNMutableNotificationContent();
         content.Body  = body;
         content.Sound = UNNotificationSound.Default;
         UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(delay, false);
         UNNotificationRequest             request = UNNotificationRequest.FromIdentifier(StringIdentifierFromInt(LocalNotificationUid), content, trigger);
         center.AddNotificationRequest(request, (NSError error) =>
         {
             if (error != null)
             {
                 Console.WriteLine("Something went wrong:" + error);
             }
         });
     }
     else
     {
         UILocalNotification localNotification = new UILocalNotification();
         localNotification.FireDate  = NSDate.FromTimeIntervalSinceNow(delay);
         localNotification.AlertBody = body;
         localNotification.TimeZone  = NSTimeZone.DefaultTimeZone;
         localNotification.UserInfo  = NSDictionary.FromObjectAndKey(NSNumber.FromInt32(LocalNotificationUid), new NSString(PWMLocalNotificationUidKey));
         UIApplication.SharedApplication.ScheduleLocalNotification(localNotification);
     }
     return(LocalNotificationUid++);
 }
示例#13
0
        void SetTextAttribute(MyLabel entity)
        {
            if (entity.Text == null)
            {
                return;
            }

            NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle()
            {
                LineSpacing = (nfloat)entity.LineSpacing,
                Alignment   = this.Control.TextAlignment,
            };

            NSMutableAttributedString attrString = new NSMutableAttributedString(entity.Text);
            NSString style = UIStringAttributeKey.ParagraphStyle;
            NSRange  range = new NSRange(0, attrString.Length);

            attrString.AddAttribute(style, paragraphStyle, range);
            attrString.AddAttribute(UIStringAttributeKey.ForegroundColor, entity.TextColor.ToUIColor(), range);
            if (entity.IsStrikeThrough)
            {
                attrString.AddAttribute(UIStringAttributeKey.StrikethroughStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

            this.Control.Font = UIFont.FromName("Myriad Pro", (nfloat)entity.FontSize);
            // Ширина текста
            CGSize size = new NSString(entity.Text).StringSize(this.Control.Font, UIScreen.MainScreen.Bounds.Width, UILineBreakMode.TailTruncation);

            this.Control.AttributedText = attrString;
        }
        private NSDictionary CreateRsaParams()
        {
            IList <object> keys   = new List <object>();
            IList <object> values = new List <object>();

            //creating the private key params
            keys.Add(IosConstants.Instance.KSecAttrApplicationTag);
            keys.Add(IosConstants.Instance.KSecAttrIsPermanent);
            keys.Add(IosConstants.Instance.KSecAttrAccessible);

            values.Add(NSData.FromString(this._keyName, NSStringEncoding.UTF8));
            values.Add(NSNumber.FromBoolean(true));
            values.Add(IosConstants.Instance.KSecAccessibleWhenUnlocked);

            NSDictionary privateKeyAttributes = NSDictionary.FromObjectsAndKeys(values.ToArray(), keys.ToArray());

            keys.Clear();
            values.Clear();

            //creating the keychain entry params
            //no need for public key params, as it will from the private key once it is needed
            keys.Add(IosConstants.Instance.KSecAttrKeyType);
            keys.Add(IosConstants.Instance.KSecAttrKeySize);
            keys.Add(IosConstants.Instance.KSecPrivateKeyAttrs);

            values.Add(IosConstants.Instance.KSecAttrKeyTypeRSA);
            values.Add(NSNumber.FromInt32(this.KeySize));
            values.Add(privateKeyAttributes);

            return(NSDictionary.FromObjectsAndKeys(values.ToArray(), keys.ToArray()));
        }
示例#15
0
        void ConfigureDataSource()
        {
            var formatter = new NSNumberFormatter {
                GroupingSize          = 3,
                UsesGroupingSeparator = true
            };

            var snapshot = InitialSnapshot();

            dataSource = new DataSource(tableView, CellProviderHandler);
            dataSource.ApplySnapshot(snapshot, false);

            UITableViewCell CellProviderHandler(UITableView tableView, NSIndexPath indexPath, NSObject obj)
            {
                var mountain = obj as MountainsController.Mountain;

                // Get a cell of the desired kind.
                var cell = tableView.DequeueReusableCell(key);

                if (cell == null)
                {
                    cell = new UITableViewCell(UITableViewCellStyle.Subtitle, key);
                }

                cell.TextLabel.Text       = mountain.Name;
                cell.DetailTextLabel.Text = formatter.StringFromNumber(NSNumber.FromInt32(mountain.Height));

                // Return the cell.
                return(cell);
            }
        }
示例#16
0
        public static void UpdateTextDecorations(this UILabel nativeLabel, ILabel label)
        {
            if (nativeLabel.AttributedText != null && !(nativeLabel.AttributedText?.Length > 0))
            {
                return;
            }

            var textDecorations = label?.TextDecorations;

            var newAttributedText     = nativeLabel.AttributedText != null ? new NSMutableAttributedString(nativeLabel.AttributedText) : new NSMutableAttributedString(label?.Text ?? string.Empty);
            var strikeThroughStyleKey = UIStringAttributeKey.StrikethroughStyle;
            var underlineStyleKey     = UIStringAttributeKey.UnderlineStyle;

            var range = new NSRange(0, newAttributedText.Length);

            if ((textDecorations & TextDecorations.Strikethrough) == 0)
            {
                newAttributedText.RemoveAttribute(strikeThroughStyleKey, range);
            }
            else
            {
                newAttributedText.AddAttribute(strikeThroughStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

            if ((textDecorations & TextDecorations.Underline) == 0)
            {
                newAttributedText.RemoveAttribute(underlineStyleKey, range);
            }
            else
            {
                newAttributedText.AddAttribute(underlineStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

            nativeLabel.AttributedText = newAttributedText;
        }
示例#17
0
        public LinkButton(IntPtr handle) : base(handle) {
            AddTrackingRect(Bounds, this, handle, true);

            _linkDict = new NSMutableDictionary() {
                { NSStringAttributeKey.ForegroundColor, NSColor.Blue },
                { NSStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single)}
            };
        }
示例#18
0
        /// <summary>
        /// Set maxFontSize for accessibility - large text
        /// </summary>
        /// <param name="label"></param>
        /// <param name="fontType"></param>
        /// <param name="text"></param>
        /// <param name="fontSize"></param>
        /// <param name="maxFontSize"></param>
        public static void InitUnderlinedLabel(UILabel label, FontType fontType, string text, float fontSize, float maxFontSize)
        {
            var attributedString = new NSMutableAttributedString(text);

            attributedString.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attributedString.Length));
            label.AttributedText = attributedString;
            label.Font           = Font(fontType, fontSize, maxFontSize);
        }
        private void ShowAppraisedValue(NSNotification obj)
        {
            var userInfo        = obj.UserInfo;
            var NotificationMsg = "";

            if (null != userInfo)
            {
                NotificationMsg = userInfo.Keys[0].ToString();
            }

            var message = userInfo.ValueForKey((Foundation.NSString) "1");

            if (NotificationMsg.Equals("1"))
            {
                Title = message.ToString();
            }

            if (!string.IsNullOrEmpty(Title))
            {
                //var a=new UILa
                string addressText          = AppDelegate.appDelegate.APNSAlertAddressa + "," + AppDelegate.appDelegate.APNSAlertAddressb + "," + AppDelegate.appDelegate.APNSAlertZip;
                var    underlineAttriString = new NSMutableAttributedString(addressText);
                underlineAttriString.AddAttribute(UIStringAttributeKey.UnderlineStyle,
                                                  NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, underlineAttriString.Length));
                address.AttributedText = underlineAttriString;
                string   Message = AppDelegate.appDelegate.APNSAlert;
                string[] tokens  = Message.Split(' ');
                VehicleDetails.Text = tokens[2] + " " + tokens[3] + " " + tokens[4];
                string   datea     = tokens[7].Substring(1);
                int      Appvalue  = Int32.Parse(datea);
                string   Appvaluea = "$" + Appvalue.ToString("#,##0");
                DateTime date      = DateTime.Now.AddDays(14);
                //string summarytext = "14 days or 500 miles";
                string formatteddate = date.ToString("MMM dd, yyyy");
                ExpDate.Text = formatteddate;
                int SummaryAppvalueStartIndex = 158;
                int SummaryAppvalueEndIndex   = Appvaluea.Length;
                int SummaryExStartIndex       = 184 + (Appvaluea.Length);
                int SummaryExEndIndex         = 20;
                var firstAttributes           = new UIStringAttributes
                {
                    Font = UIFont.BoldSystemFontOfSize(14)
                };

                var secondAttributes = new UIStringAttributes
                {
                    ForegroundColor    = UIColor.Red,
                    BackgroundColor    = UIColor.Gray,
                    StrikethroughStyle = NSUnderlineStyle.Single
                };
                var prettyString = new NSMutableAttributedString("Thank you for submitting your appraisal information. We are happy to provide a value based on the information you have provided us. Your vehicle is valued at " + Appvaluea + ". This amount is good for 14 days or 500 miles from the date of submission. At the time of delivery or transfer of ownership, CarCash reserves the right to verify that the information you have submitted is accurate and to adjust the value offered if we feel that your vehicle does not match the description you have provided.!");
                prettyString.SetAttributes(firstAttributes.Dictionary, new NSRange(SummaryAppvalueStartIndex, SummaryAppvalueEndIndex));
                prettyString.SetAttributes(firstAttributes.Dictionary, new NSRange(SummaryExStartIndex, SummaryExEndIndex));
                //prettyString.SetAttributes(firstAttributes.Dictionary, new NSRange(0, 11));
                APNSSummary.AttributedText = prettyString;
            }
        }
示例#20
0
        /// <summary>
        /// Updates the UI.
        /// </summary>
        /// <param name="view">
        /// The view.
        /// </param>
        /// <param name="control">
        /// The control.
        /// </param>
        private static void UpdateUi(ExtendedLabel view, UILabel control)
        {
            if (view.FontSize > 0)
            {
                control.Font = UIFont.FromName(control.Font.Name, (float)view.FontSize);
            }

            if (!string.IsNullOrEmpty(view.FontName))
            {
                string fontName = view.FontName;
                //if extension given then remove it for iOS
                if (fontName.LastIndexOf(".", System.StringComparison.Ordinal) == fontName.Length - 4)
                {
                    fontName = fontName.Substring(0, fontName.Length - 4);
                }

                var font = UIFont.FromName(
                    fontName, control.Font.PointSize);

                if (font != null)
                {
                    control.Font = font;
                }
            }

            //======= This is for backward compatability with obsolete attrbute 'FontNameIOS' ========
            if (!string.IsNullOrEmpty(view.FontNameIOS))
            {
                var font = UIFont.FromName(
                    view.FontNameIOS,
                    (view.FontSize > 0) ? (float)view.FontSize : 12.0f);

                if (font != null)
                {
                    control.Font = font;
                }
            }
            //====== End of obsolete section ==========================================================

            var attrString = new NSMutableAttributedString(control.Text);

            if (view.IsUnderline)
            {
                //control.AttributedText = new NSAttributedString(
                //    control.Text,
                //    underlineStyle: NSUnderlineStyle.Single);

                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            if (view.IsStrikeThrough)
            {
                attrString.AddAttribute(UIStringAttributeKey.StrikethroughStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
示例#21
0
        public static void Record(string url)
        {
            var parameters = HttpUtility.ParseQueryString(url.Substring(url.IndexOf('?')));

            if (parameters != null)
            {
                if (parameters.ContainsKey("callback"))
                {
                    callback = parameters ["callback"];
                }
                else
                {
                    throw new ArgumentException("Audio recording requires a callback URI.");
                }
            }

            NSObject[] values = new NSObject[]
            {
                NSNumber.FromInt32((int)AudioFormatType.MPEG4AAC),
                NSNumber.FromInt32(2),
                NSNumber.FromInt32((int)AVAudioQuality.Max)
            };

            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVEncoderAudioQualityKey
            };

            NSDictionary settings = NSDictionary.FromObjectsAndKeys(values, keys);

            string audioFilePath = Path.Combine(TouchFactory.Instance.TempPath, Guid.NewGuid().ToString() + ".aac");

            NSError error = null;

            audioRecorder = AVAudioRecorder.Create(NSUrl.FromFilename(audioFilePath), new AudioSettings(settings), out error);

            var actionSheet = new UIActionSheet(string.Empty)
            {
                TouchFactory.Instance.GetResourceString("RecordAudio"),
                TouchFactory.Instance.GetResourceString("Cancel"),
            };

            actionSheet.CancelButtonIndex = 1;
            actionSheet.Style             = UIActionSheetStyle.BlackTranslucent;
            actionSheet.ShowInView(TouchFactory.Instance.TopViewController.View);
            actionSheet.Clicked += delegate(object sender, UIButtonEventArgs args)
            {
                switch (args.ButtonIndex)
                {
                case 0:
                    StartRecording();
                    break;
                }
            };
        }
示例#22
0
        protected override void OnElementChanged(ElementChangedEventArgs <Label> e)
        {
            base.OnElementChanged(e);
            var label = Control;
            var text  = label.AttributedText as NSMutableAttributedString;
            var range = new NSRange(0, text.Length);

            text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
        }
示例#23
0
        //public NSDictionary OutputIntent { get; set; }

        internal override NSMutableDictionary ToDictionary()
        {
            var ret = base.ToDictionary();

            if (Title != null)
            {
                ret.LowlevelSetObject((NSString)Title, kCGPDFContextTitle);
            }
            if (Author != null)
            {
                ret.LowlevelSetObject((NSString)Author, kCGPDFContextAuthor);
            }
            if (Subject != null)
            {
                ret.LowlevelSetObject((NSString)Subject, kCGPDFContextSubject);
            }
            if (Keywords != null && Keywords.Length > 0)
            {
                if (Keywords.Length == 1)
                {
                    ret.LowlevelSetObject((NSString)Keywords [0], kCGPDFContextKeywords);
                }
                else
                {
                    ret.LowlevelSetObject(NSArray.FromStrings(Keywords), kCGPDFContextKeywords);
                }
            }
            if (Creator != null)
            {
                ret.LowlevelSetObject((NSString)Creator, kCGPDFContextCreator);
            }
            if (OwnerPassword != null)
            {
                ret.LowlevelSetObject((NSString)OwnerPassword, kCGPDFContextOwnerPassword);
            }
            if (UserPassword != null)
            {
                ret.LowlevelSetObject((NSString)UserPassword, kCGPDFContextUserPassword);
            }
            if (EncryptionKeyLength.HasValue)
            {
                ret.LowlevelSetObject(NSNumber.FromInt32(EncryptionKeyLength.Value), kCGPDFContextEncryptionKeyLength);
            }
            if (AllowsPrinting.HasValue && AllowsPrinting.Value == false)
            {
                ret.LowlevelSetObject(CFBoolean.FalseHandle, kCGPDFContextAllowsPrinting);
            }
            if (AllowsCopying.HasValue && AllowsCopying.Value == false)
            {
                ret.LowlevelSetObject(CFBoolean.FalseHandle, kCGPDFContextAllowsCopying);
            }
            if (AccessPermissions.HasValue)
            {
                ret.LowlevelSetObject(NSNumber.FromInt32((int)AccessPermissions.Value), kCGPDFContextAccessPermissions);
            }
            return(ret);
        }
示例#24
0
        public void PrepareRecorder()
        {
            if (Recorder != null)
            {
                Recorder.Dispose();
            }
            var audioSession = AVAudioSession.SharedInstance();
            var err          = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

            if (err != null)
            {
                Console.WriteLine("audioSession: {0}", err);
            }
            err = audioSession.SetActive(true);
            if (err != null)
            {
                Console.WriteLine("audioSession: {0}", err);
            }

            Console.WriteLine("Audio File Path: " + AudioFilePath + AudioFileName);
            Url = NSUrl.FromFilename(AudioFilePath + AudioFileName + ".mp4");

            if (File.Exists(AudioFilePath + "/" + AudioFileName + ".mp4"))
            {
                File.Delete(AudioFilePath + "/" + AudioFileName + ".mp4");
            }

            //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
            NSObject[] values = new NSObject[] {
                NSNumber.FromFloat(44100.0f),
                //Sample Rate
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.LinearPCM),
                //AVFormat
                NSNumber.FromInt32(2),
                //Channels
                NSNumber.FromInt32(16),
                //PCMBitDepth
                NSNumber.FromBoolean(false),
                //IsBigEndianKey
                NSNumber.FromBoolean(false)
                //IsFloatKey
            };
            //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
            NSObject[] keys = new NSObject[] {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            Settings = NSDictionary.FromObjectsAndKeys(values, keys);
            Recorder = AVAudioRecorder.Create(Url, new AudioSettings(Settings), out Error);
            Recorder.PrepareToRecord();
        }
示例#25
0
        private bool PrepareVariables()
        {
            var audioSession = AVAudioSession.SharedInstance();
            var err          = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

            if (err != null)
            {
                Console.WriteLine($"audioSession: {err}");
                return(false);
            }
            err = audioSession.SetActive(true);
            if (err != null)
            {
                Console.WriteLine($"audioSession: {err}");
                return(false);
            }
            //Declare string for application temp path and tack on the file extension
            string fileName = $"Myfile{DateTime.Now.ToString("yyyyMMddHHmmss")}.wav";

            audioFilePath = Path.Combine(Path.GetTempPath(), fileName);

            Console.WriteLine("Audio File Path: " + audioFilePath);

            url = NSUrl.FromFilename(audioFilePath);
            //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
            NSObject[] values =
            {
                NSNumber.FromFloat(44100.0f),                                    //Sample Rate
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
                NSNumber.FromInt32(2),                                           //Channels
                NSNumber.FromInt32(16),                                          //PCMBitDepth
                NSNumber.FromBoolean(false),                                     //IsBigEndianKey
                NSNumber.FromBoolean(false)                                      //IsFloatKey
            };

            //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
            NSObject[] keys =
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            //Set Settings with the Values and Keys to create the NSDictionary
            settings = NSDictionary.FromObjectsAndKeys(values, keys);

            //Set recorder parameters
            recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);

            //Set Recorder to Prepare To Record
            recorder.PrepareToRecord();
            return(true);
        }
        void UpdateTextDecorations()
        {
            if (Element?.TextType != TextType.Text)
            {
                return;
            }
#if __MOBILE__
            if (!(Control.AttributedText?.Length > 0))
            {
                return;
            }
#else
            if (!(Control.AttributedStringValue?.Length > 0))
            {
                return;
            }
#endif

            var textDecorations = Element.TextDecorations;
#if __MOBILE__
            var newAttributedText     = new NSMutableAttributedString(Control.AttributedText);
            var strikeThroughStyleKey = UIStringAttributeKey.StrikethroughStyle;
            var underlineStyleKey     = UIStringAttributeKey.UnderlineStyle;
#else
            var newAttributedText     = new NSMutableAttributedString(Control.AttributedStringValue);
            var strikeThroughStyleKey = NSStringAttributeKey.StrikethroughStyle;
            var underlineStyleKey     = NSStringAttributeKey.UnderlineStyle;
#endif
            var range = new NSRange(0, newAttributedText.Length);

            if ((textDecorations & TextDecorations.Strikethrough) == 0)
            {
                newAttributedText.RemoveAttribute(strikeThroughStyleKey, range);
            }
            else
            {
                newAttributedText.AddAttribute(strikeThroughStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

            if ((textDecorations & TextDecorations.Underline) == 0)
            {
                newAttributedText.RemoveAttribute(underlineStyleKey, range);
            }
            else
            {
                newAttributedText.AddAttribute(underlineStyleKey, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

#if __MOBILE__
            Control.AttributedText = newAttributedText;
#else
            Control.AttributedStringValue = newAttributedText;
#endif
            UpdateCharacterSpacing();
            _perfectSizeValid = false;
        }
        /// <summary>
        ///    Set underline for range.
        /// </summary>
        /// <param name="self">Target.</param>
        /// <param name="underlineStyle">Style.</param>
        /// <param name="range">Range to set underline.</param>
        /// <returns>Modified instance of <see cref="T:Foundation.NSMutableAttributedString"/>.</returns>
        public static NSMutableAttributedString Underline(
            this NSMutableAttributedString self,
            NSUnderlineStyle underlineStyle = NSUnderlineStyle.Single,
            NSRange?range = null)
        {
            var value = NSNumber.FromInt32((int)underlineStyle);

            self.AddAttribute(UIStringAttributeKey.UnderlineStyle, value, range ?? new NSRange(0, self.Length));
            return(self);
        }
示例#28
0
        static NSAttributedString GetAttributedString(string text)
        {
            var attrStr = new NSMutableAttributedString(text);
            var range   = new NSRange(0, attrStr.Length);

            attrStr.AddAttribute(NSAttributedString.ForegroundColorAttributeName, NSColor.Blue, range);
            attrStr.AddAttribute(NSAttributedString.UnderlineStyleAttributeName, NSNumber.FromInt32((int)MonoMac.AppKit.NSUnderlineStyle.Single), range);

            return(attrStr);
        }
示例#29
0
            public bool SetupAssetWriterAudioInput(CMFormatDescription currentFormatDescription)
            {
                // If the AudioStreamBasicDescription is null return false;
                if (!currentFormatDescription.AudioStreamBasicDescription.HasValue)
                {
                    return(false);
                }

                var currentASBD = currentFormatDescription.AudioStreamBasicDescription.Value;

                // Get the Audio Channel Layout from the Format Description.
                var currentChannelLayout     = currentFormatDescription.AudioChannelLayout;
                var currentChannelLayoutData = currentChannelLayout == null ? new NSData() : currentChannelLayout.AsData();

                NSDictionary audioCompressionSettings = NSDictionary.FromObjectsAndKeys(
                    new NSObject[]
                {
                    NSNumber.FromInt32((int)AudioFormatType.MPEG4AAC),
                    NSNumber.FromDouble(currentASBD.SampleRate),
                    NSNumber.FromInt32(64000),
                    NSNumber.FromInt32(currentASBD.ChannelsPerFrame),
                    currentChannelLayoutData
                },
                    new NSObject[]
                {
                    AVAudioSettings.AVFormatIDKey,
                    AVAudioSettings.AVSampleRateKey,
                    AVAudioSettings.AVEncoderBitRateKey,
                    AVAudioSettings.AVNumberOfChannelsKey,
                    new NSString("AVChannelLayoutKey")                             //AVAudioSettings.AVChannelLayoutKey,
                });

                if (processor.assetWriter.CanApplyOutputSettings(audioCompressionSettings, AVMediaType.Audio))
                {
                    processor.assetWriterAudioIn = new AVAssetWriterInput(AVMediaType.Audio, audioCompressionSettings);
                    processor.assetWriterAudioIn.ExpectsMediaDataInRealTime = true;

                    if (processor.assetWriter.CanAddInput(processor.assetWriterAudioIn))
                    {
                        processor.assetWriter.AddInput(processor.assetWriterAudioIn);
                    }
                    else
                    {
                        Console.WriteLine("Couldn't add asset writer audio input.");
                        return(false);
                    }
                }
                else
                {
                    Console.WriteLine("Couldn't apply audio output settings.");
                    return(false);
                }

                return(true);
            }
示例#30
0
        void ConfigureDataSource()
        {
            dataSource = new UICollectionViewDiffableDataSource <NSNumber, NSNumber> (collectionView, CellProviderHandler)
            {
                SupplementaryViewProvider = SupplementaryViewProviderHandler
            };

            // initial data
            var snapshot        = new NSDiffableDataSourceSnapshot <NSNumber, NSNumber> ();
            var idOffset        = 0;
            var itemsPerSection = 18;

            foreach (var section in SectionKind.AllSections)
            {
                snapshot.AppendSections(new [] { NSNumber.FromInt32(section.EnumValue) });
                var items = Enumerable.Range(idOffset, itemsPerSection).Select(i => NSNumber.FromInt32(i)).ToArray();
                snapshot.AppendItems(items);
                idOffset += itemsPerSection;
            }

            dataSource.ApplySnapshot(snapshot, false);

            UICollectionViewCell CellProviderHandler(UICollectionView collectionView, NSIndexPath indexPath, NSObject obj)
            {
                // Get a cell of the desired kind.
                var cell = collectionView.DequeueReusableCell(TextCell.Key, indexPath) as TextCell;

                // Populate the cell with our item description.
                cell.Label.Text = $"{indexPath.Section}, {indexPath.Row}";
                cell.ContentView.BackgroundColor    = UIColorExtensions.CornflowerBlue;
                cell.ContentView.Layer.BorderColor  = UIColor.Black.CGColor;
                cell.ContentView.Layer.BorderWidth  = 1;
                cell.ContentView.Layer.CornerRadius = 8;
                cell.Label.TextAlignment            = UITextAlignment.Center;
                cell.Label.Font = UIFont.GetPreferredFontForTextStyle(UIFontTextStyle.Title1);

                // Return the cell.
                return(cell);
            }

            UICollectionReusableView SupplementaryViewProviderHandler(UICollectionView collectionView, string kind, NSIndexPath indexPath)
            {
                var sectionKind = SectionKind.GetSectionKind(indexPath.Section);

                // Get a supplementary view of the desired kind.
                var header = collectionView.DequeueReusableSupplementaryView(new NSString(kind),
                                                                             TitleSupplementaryView.Key, indexPath) as TitleSupplementaryView;

                // Populate the view with our section's description.
                header.Label.Text = $".{sectionKind}";

                // Return the view.
                return(header);
            }
        }