Esempio n. 1
0
        public DetailViewController(RSSFeedItem item)
            : base(UITableViewStyle.Grouped, null, true)
        {
            var attributes = new NSAttributedStringDocumentAttributes();

            attributes.DocumentType   = NSDocumentType.HTML;
            attributes.StringEncoding = NSStringEncoding.UTF8;
            var error      = new NSError();
            var htmlString = new NSAttributedString(item.Description, attributes, ref error);


            Root = new RootElement(item.Title)
            {
                new Section {
                    new StringElement(item.Author),
                    new StringElement(item.PublishDate),
                    new StyledMultilineElement(htmlString),
                    new HtmlElement("Full Article", item.Link)
                }
            };

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, async delegate
            {
                var message = item.Title + " " + item.Link + " #PlanetXamarin";
                var social  = new UIActivityViewController(new NSObject[] { new NSString(message) },
                                                           new UIActivity[] { new UIActivity() });
                PresentViewController(social, true, null);
            });
        }
        private void UpdateText()
        {
            if (Control == null || Element == null)
            {
                return;
            }

            var isHtml = HtmlLabel.GetIsHtml(Element);

            if (!isHtml)
            {
                return;
            }

            var removeTags = HtmlLabel.GetRemoveHtmlTags(Element);

            if (removeTags)
            {
                Control.Text = HtmlToText.ConvertHtml(Control.Text);
            }
            else
            {
                var value   = Element.Text ?? string.Empty;
                var attr    = new NSAttributedStringDocumentAttributes();
                var nsError = new NSError();
                attr.DocumentType = NSDocumentType.HTML;

                var myHtmlData = NSData.FromString(value, NSStringEncoding.Unicode);
                Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
            }
            SetNeedsDisplay();
        }
Esempio n. 3
0
        public static NSAttributedString ToAttributedString(this NSString source)
        {
            try
            {
                NSError error      = null;
                var     data       = NSData.FromString(source, NSStringEncoding.UTF8);
                var     attributes = new NSAttributedStringDocumentAttributes
                {
                    DocumentType   = NSDocumentType.HTML,
                    StringEncoding = NSStringEncoding.UTF8,
                };
                var attributedString = new NSAttributedString(data, attributes, ref error);

                if (error != null)
                {
                    return(new NSAttributedString());
                }

                return(attributedString);
            }
            catch
            {
                return(new NSAttributedString());
            }
        }
Esempio n. 4
0
        void UpdateTextHtml()
        {
            string text = Element.Text ?? string.Empty;

#if __MOBILE__
            var attr = new NSAttributedStringDocumentAttributes
            {
                DocumentType = NSDocumentType.HTML
            };

            NSError nsError = null;

            Control.AttributedText = new NSAttributedString(text, attr, ref nsError);
#else
            var attr = new NSAttributedStringDocumentAttributes
            {
                DocumentType = NSDocumentType.HTML
            };

            var htmlData = new NSMutableData();
            htmlData.SetData(text);

            Control.AttributedStringValue = new NSAttributedString(htmlData, attr, out _);
#endif
            _perfectSizeValid = false;
        }
Esempio n. 5
0
        protected override void OnElementChanged(ElementChangedEventArgs <Label> e)
        {
            base.OnElementChanged(e);

            var view = (HtmlFormattedLabel)Element;

            if (view == null)
            {
                return;
            }
            if (view.Text == null)
            {
                return;
            }

            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType   = NSDocumentType.HTML;
            attr.StringEncoding = NSStringEncoding.UTF8;

            //Append the html string with a style tag. This will make the fontsize and fontfamily attribute on a label work on HtmlFormattedLabel
            var styles = @"<style>body{font - family: " + Element.FontFamily + "; font-size:" + Element.FontSize + "px;}</style>";
            var htmlStringWithStyle = Element.Text + styles;

            var myHtmlData = NSData.FromString(htmlStringWithStyle, NSStringEncoding.UTF8);

            Control.Lines          = 0;
            Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
        }
Esempio n. 6
0
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == Label.TextProperty.PropertyName)
            {
                if (Control != null && Element != null && !string.IsNullOrWhiteSpace(Element.Text))
                {
                    var attr    = new NSAttributedStringDocumentAttributes();
                    var nsError = new NSError();
                    attr.DocumentType   = NSDocumentType.HTML;
                    attr.StringEncoding = NSStringEncoding.UTF8;

                    if (Element.Text != null && Element.Text != "")
                    {
                        //Append the html string with a style tag. This will make the fontsize and fontfamily attribute on a label work on HtmlFormattedLabel
                        var styles = @"<style>body{font - family: " + Element.FontFamily + "; font-size:" + Element.FontSize + "px;}</style>";
                        var htmlStringWithStyle = Element.Text + styles;

                        var myHtmlData = NSData.FromString(htmlStringWithStyle, NSStringEncoding.UTF8);

                        Control.Lines          = 0;
                        Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
                    }
                }
            }
        }
        // <summary>
        /// Set maxFontSize for accessibility - large text
        /// </summary>
        /// <param name="label"></param>
        /// <param name="fontType"></param>
        /// <param name="rawText"></param>
        /// <param name="lineHeight"></param>
        /// <param name="fontSize"></param>
        /// <param name="maxFontSize"></param>
        /// <param name="alignment"></param>
        public static void InitUITextViewWithSpacingAndUrl(UITextView label, FontType fontType, string rawText, double lineHeight, float fontSize, float maxFontSize, UITextAlignment alignment = UITextAlignment.Left)
        {
            //Defining attibutes inorder to format the embedded link
            NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML
            };

            documentAttributes.StringEncoding = NSStringEncoding.UTF8;
            NSError            error            = null;
            NSAttributedString attributedString = new NSAttributedString(NSData.FromString(rawText, NSStringEncoding.UTF8), documentAttributes, ref error);

            NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();

            paragraphStyle.LineHeightMultiple = new nfloat(lineHeight);
            paragraphStyle.Alignment          = alignment;
            NSMutableAttributedString text = new NSMutableAttributedString(attributedString);
            NSRange range = new NSRange(0, text.Length);

            text.AddAttribute(UIStringAttributeKey.ParagraphStyle, paragraphStyle, range);
            text.AddAttribute(UIStringAttributeKey.Font, Font(fontType, fontSize, maxFontSize), range);
            label.AttributedText = text;

            label.TextColor = UIColor.White;
            label.WeakLinkTextAttributes = new NSDictionary(UIStringAttributeKey.ForegroundColor, "#FADC5D".ToUIColor(), UIStringAttributeKey.UnderlineStyle, new NSNumber(1));
        }
Esempio n. 8
0
        void initResizableText()
        {
            //ATT fpr HTML
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;


            contentLabel = new UILabel(new CGRect(24, 0, 720, 100));
            contentLabel.LineBreakMode = UILineBreakMode.WordWrap;
            contentLabel.TextColor     = source.Color;         // UIColor.Purple;
            contentLabel.Font          = UIFont.FromName(fontName, 24);
            //contentLabel.Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. quis nostrud exercitation END";
            //contentLabel.Text = source.Paragraph ;

            var myHtmlText = source.Paragraph;             //"<b>Hello</b> <i>Everyone</i> ÆØÅ";
            var myHtmlData = NSData.FromString(myHtmlText, NSStringEncoding.Unicode);

            contentLabel.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
            contentLabel.Font           = UIFont.FromName(fontName, 24);

            contentHeight = YConstants.ResizeHeigthWithText(contentLabel, maxHeight: 960f);

            authorLabel = new UILabel(new CGRect(24, contentHeight + 12, 500, 24));
            authorLabel.LineBreakMode = UILineBreakMode.WordWrap;
            authorLabel.TextColor     = UIColor.Gray;
            authorLabel.Font          = UIFont.FromName(fontName, 16);
            //authorLabel.Text = "Author de la frase";
            authorLabel.Text = source.Author;
            authorHeight     = YConstants.ResizeHeigthWithText(authorLabel, maxHeight: 960f);

            borderHeight = authorHeight + contentHeight + 12;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            EdgesForExtendedLayout = UIRectEdge.None;

            UIScrollView scrollView = new UIScrollView();

            scrollView.TranslatesAutoresizingMaskIntoConstraints = false;
            View.AddSubview(scrollView);

            TextContentLabel       = new UILabel();
            TextContentLabel.Lines = 0;
            TextContentLabel.TranslatesAutoresizingMaskIntoConstraints = false;
            scrollView.AddSubview(TextContentLabel);

            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            TextContentLabel.AttributedText = new NSAttributedString(TextToView, attr, ref nsError);


            var viewsDictionary = NSDictionary.FromObjectsAndKeys(new NSObject[] { scrollView, TextContentLabel }, new NSObject[] { new NSString("scrollView"), new NSString("TextContentLabel") });

            scrollView.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[TextContentLabel(scrollView)]|", 0, null, viewsDictionary));
            scrollView.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[TextContentLabel]|", 0, null, viewsDictionary));
            View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|-[scrollView]-|", 0, null, viewsDictionary));
            View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|-[scrollView]-|", 0, null, viewsDictionary));
        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            var view = (HtmlLabel)Element;

            if (view == null || string.IsNullOrEmpty(view.Text))
            {
                return;
            }

            UITextView textView;

            if (Control == null)
            {
                textView = new UITextView();
                SetNativeControl(textView);
            }
            else if (e.PropertyName == Label.TextProperty.PropertyName)
            {
                if (Element != null && !string.IsNullOrWhiteSpace(Element.Text))
                {
                    var attr    = new NSAttributedStringDocumentAttributes();
                    var nsError = new NSError();
                    attr.DocumentType = NSDocumentType.HTML;

                    var text       = "<style>body{font-family: '" + this.Control.Font.Name + "'; font-size:" + this.Control.Font.PointSize + "px;}</style>" + view.Text;
                    var myHtmlData = NSData.FromString(ParseText(text), NSStringEncoding.Unicode);
                    Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
                }
            }
        }
Esempio n. 11
0
        protected override void OnElementChanged(ElementChangedEventArgs <Label> e)
        {
            base.OnElementChanged(e);

#if __ANDROID__
            if ((int)Build.VERSION.SdkInt >= 24)
            {
                Control?.SetText(Html.FromHtml(Element.Text, FromHtmlOptions.ModeLegacy), TextView.BufferType.Spannable); // SDK >= Android N
            }
            else
            {
                Control?.SetText(Html.FromHtml(Element.Text), TextView.BufferType.Spannable);
            }
#elif __IOS__
            if (Control != null && !string.IsNullOrWhiteSpace(Element?.Text))
            {
                var attr    = new NSAttributedStringDocumentAttributes();
                var nsError = new NSError();
                attr.DocumentType = NSDocumentType.HTML;

                var myHtmlData = NSData.FromString(Element.Text, NSStringEncoding.Unicode);
                Control.Lines          = 0;
                Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
            }
#elif WINDOWS_UWP
            //TODO: Not sure what is needed here to render HTML on UWP
            // Looks like what I need might be here:
            // https://github.com/ryanvalentin/UWP-RichTextControls/blob/master/RichTextControls/RichTextControls/Generators/HtmlXamlGenerator.cs
#endif
        }
        private NSMutableAttributedString ApplyStylingToText(string text, FontType fontType, double lineHeight = 1.28, int fontSize = 16, int maxFontSize = 22, bool isLink = false)
        {
            //Wraps the string containing HTML, with styling tags inorder to ensure correct font, color, size.
            string html = HtmlWrapper.HtmlForLabelWithText(text, 16, false, false, "#ffffff");

            //Defining document type as HTML, set string encoding and formats an attributed string with these.
            NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML
            };

            documentAttributes.StringEncoding = NSStringEncoding.UTF8;
            NSError            error            = null;
            NSAttributedString attributedString = new NSAttributedString(NSData.FromString(html, NSStringEncoding.UTF8), documentAttributes, ref error);

            NSMutableAttributedString attributedTextToAppend = new NSMutableAttributedString(attributedString);

            attributedTextToAppend.DeleteRange(new NSRange(attributedTextToAppend.Length - 1, 1));
            NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle
            {
                LineHeightMultiple = new nfloat(lineHeight)
            };

            NSRange range = new NSRange(0, attributedTextToAppend.Length);

            attributedTextToAppend.AddAttribute(UIStringAttributeKey.ParagraphStyle, paragraphStyle, range);
            attributedTextToAppend.AddAttribute(UIStringAttributeKey.Font, Font(fontType, fontSize, maxFontSize), range);

            //Add a hyperlink to this text, makes text clickable
            if (isLink)
            {
                attributedTextToAppend.AddAttribute(UIStringAttributeKey.Link, new NSUrl("https://www." + text), range);
            }

            return(attributedTextToAppend);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes
            {
                DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8
            };
            NSError            error            = null;
            NSAttributedString attributedString =
                new NSAttributedString(NSData.FromString(ForceUpdateViewModel.FORCE_UPDATE_MESSAGE, NSStringEncoding.UTF8), documentAttributes, ref error);

            if (error != null)
            {
                LogUtils.LogMessage(Enums.LogSeverity.ERROR, error.LocalizedDescription);
            }

            //Ensuring text is resiezed correctly when font size is increased
            StyleUtil.InitLabekWithSpacingAndHTMLFormatting(
                TextLabel, StyleUtil.FontType.FontBold, attributedString, 1.28, 24, 30, UITextAlignment.Center);
            TextLabel.TextColor = ColorHelper.TEXT_COLOR_ON_BACKGROUND;

            StyleUtil.InitButtonStyling(AppStoreLinkButton, ForceUpdateViewModel.FORCE_UPDATE_BUTTON_APPSTORE_IOS);
            AppStoreLinkButton.AccessibilityTraits = UIAccessibilityTrait.Link;

            FhiLogo.AccessibilityLabel   = ForceUpdateViewModel.SMITTESPORING_FHI_LOGO_ACCESSIBILITY;
            TextLabel.AccessibilityLabel = AccessibilityUtils.RemovePoorlySpokenSymbolsString(ForceUpdateViewModel.FORCE_UPDATE_MESSAGE);
        }
Esempio n. 14
0
        protected override NSAttributedString Convert(string value, Type targetType, object parameter, CultureInfo culture)
        {
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            //var label = parameter as UILabel;

            //nfloat red = 0.0f;
            //nfloat green = 0.0f;
            //nfloat blue = 0.0f;
            //nfloat alpha = 0.0f;
            //label.TextColor.GetRGBA(out red, out green, out blue, out alpha);

            //var stringWithFont = value + string.Format(
            //	"<style>body{{font-family: '{0}'; font-size:{1}px; color:rgb({2}, {3}, {4})}}</style>"
            //   , label.Font.Name
            //   , label.Font.PointSize
            //   , red * 255
            //   , green * 255
            //   , blue * 255);

            var htmlData = NSData.FromString(value, NSStringEncoding.UTF8);
            var attrStr  = new NSAttributedString(htmlData, attr, ref nsError);

            return(attrStr);
        }
        public DetailViewController(RSSFeedItem item)
            : base(UITableViewStyle.Grouped, null, true)
        {
            var attributes = new NSAttributedStringDocumentAttributes();
              attributes.DocumentType = NSDocumentType.HTML;
              attributes.StringEncoding = NSStringEncoding.UTF8;
              var error = new NSError();
              var htmlString = new NSAttributedString(item.Description, attributes, ref error);

              Root = new RootElement(item.Title) {
                new Section{
                new StringElement(item.Author),
                new StringElement(item.PublishDate),
                        new StyledMultilineElement(htmlString),
                new HtmlElement("Full Article", item.Link)
              }
            };

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, async delegate
                {
                    var message = item.Title + " " + item.Link + " #PlanetXamarin";
                    var social = new UIActivityViewController(new NSObject[] { new NSString(message)},
                        new UIActivity[] { new UIActivity() });
                    PresentViewController(social, true, null);
                });
        }
        private void CreateAttributedString(UILabel control, string html)
        {
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            var fontDescriptor = control.Font.FontDescriptor.VisibleName;
            var fontFamily     = fontDescriptor.ToLower().Contains("system") ? "-apple-system,system-ui,BlinkMacSystemFont,Segoe UI" : control.Font.FamilyName;

            html += "<style> body{ font-family: " + fontFamily + ";}</style>";
            // --------------
            var myHtmlData = NSData.FromString(html, NSStringEncoding.Unicode);
            // control.Lines = 0;
            var mutable = new NSMutableAttributedString(new NSAttributedString(myHtmlData, attr, ref nsError));

            if (mutable.MutableString.HasSuffix(new NSString("\n")))
            {
                mutable.DeleteRange(new NSRange(mutable.MutableString.Length - 1, 1));
            }

            var links = new List <LinkData>();

            control.AttributedText = mutable;
        }
Esempio n. 17
0
        public void EmitText(FormattedText text)
        {
            if (text.Attributes.Count == 0)
            {
                EmitText(text.Text, RichTextInlineStyle.Normal);
                return;
            }
            var s       = text.ToAttributedString();
            var options = new NSAttributedStringDocumentAttributes();

            options.DocumentType = NSDocumentType.HTML;
            var exclude = NSArray.FromObjects(new [] { "doctype", "html", "head", "meta", "xml", "body", "p" });

            options.Dictionary [NSExcludedElementsDocumentAttribute] = exclude;
            NSError err;
            var     d   = s.GetData(new NSRange(0, s.Length), options, out err);
            var     str = (string)NSString.FromData(d, NSStringEncoding.UTF8);


            //bool first = true;
            foreach (string line in str.Split(lineSplitChars, StringSplitOptions.None))
            {
                //if (!first) {
                //	xmlWriter.WriteStartElement ("br");
                //	xmlWriter.WriteEndElement ();
                //} else
                //	first = false;
                xmlWriter.WriteRaw(line);
            }
        }
Esempio n. 18
0
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == Label.TextProperty.PropertyName)
            {
                if (Control != null && Element != null && !string.IsNullOrWhiteSpace(Element.Text))
                {
                    var attr    = new NSAttributedStringDocumentAttributes();
                    var nsError = new NSError();
                    attr.DocumentType = NSDocumentType.HTML;


                    Control.TextColor.GetRGBA(out nfloat r, out nfloat g, out nfloat b, out nfloat a);
                    var textColor = string.Format("#{0:X2}{1:X2}{2:X2}", (int)(r * 255.0), (int)(g * 255.0), (int)(b * 255.0));

                    var font         = Control.Font;
                    var fontName     = font.Name;
                    var fontSize     = font.PointSize;
                    var htmlContents = "<span style=\"font-family: '" + fontName + "'; color: " + textColor + "; font-size: " + fontSize + "\">" + Element.Text + "</span>";
                    var myHtmlData   = NSData.FromString(htmlContents, NSStringEncoding.Unicode);

                    Control.Lines          = 0;
                    Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
                }
            }
        }
Esempio n. 19
0
        protected override void OnElementChanged(ElementChangedEventArgs <Label> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement == null)
            {
                return;
            }
            if (Control == null)
            {
                return;
            }
            Control.Font = Font.RobotoLight(15f);

            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            var text = e.NewElement.Text;

            //I wrap the text here with the default font and size
            text = "<style>body{font-family: '" + this.Control.Font.Name + "'; font-size:" + this.Control.Font.PointSize + "px;}</style>" + text;

            var myHtmlData = NSData.FromString(text, NSStringEncoding.Unicode);

            Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
        }
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            var view = (HyperLinkControl)Element;

            if (view == null)
            {
                return;
            }

            UITextView textView;

            if (Control == null)
            {
                textView = new UITextView();
                SetNativeControl(textView);
            }
            else if (e.PropertyName == Label.TextProperty.PropertyName)
            {
                if (Element != null && !string.IsNullOrWhiteSpace(Element.Text))
                {
                    var attr    = new NSAttributedStringDocumentAttributes();
                    var nsError = new NSError();
                    attr.DocumentType = NSDocumentType.HTML;

                    var myHtmlData = NSData.FromString(view.Text, NSStringEncoding.Unicode);
                    Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
                }
            }
        }
Esempio n. 21
0
        private void SetHtmlText()
        {
            var element = (this.Element as AppLabel);

            if ((element != null) && (!String.IsNullOrEmpty(element.HtmlText)))
            {
                try
                {
                    var attr = new NSAttributedStringDocumentAttributes();
                    var nsError = new NSError();
                    attr.DocumentType = NSDocumentType.HTML;

                    nfloat r, g, b, a;
                    var elementColor = element.TextColor.ToUIColor();
                    elementColor.GetRGBA(out r, out g, out b, out a);
                    var textColor = string.Format("#{0:X2}{1:X2}{2:X2}", (int)(r * 255.0), (int)(g * 255.0), (int)(b * 255.0));

                    var html = element.HtmlText + String.Format("<style>body{{font-family: '{0}'; font-size:{1}px; color:{2}}}</style>", this.Control.Font.Name, this.Control.Font.PointSize, textColor);

                    var myHtmlData = NSData.FromString(html, NSStringEncoding.Unicode);

                    var attributedString = new NSAttributedString(myHtmlData, attr, ref nsError);

                    this.Control.AttributedText = attributedString;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
        }
            public override UIView GetViewForHeader(UITableView tableView, nint section)
            {
                UITableViewCell header = new UITableViewCell(UITableViewCellStyle.Default, HeaderIdentifier);

                header.TextLabel.Font = Styles.SetHelveticaFont(17);


                var attr    = new NSAttributedStringDocumentAttributes();
                var nsError = new NSError();

                attr.DocumentType = NSDocumentType.HTML;

                if (section == 0)
                {
                    var html      = String.Format(AppDelegate.LanguageBundle.GetLocalizedString("alerts_not_read"), "<b><font color='red'>" + alerts.Where(x => !x.Read).Count().ToString() + "</font></b>");
                    var htmlStyle = string.Format("<style>body{{font-family:'{0}'; font-size:{1}px;}}</style>",
                                                  header.TextLabel.Font.FamilyName,
                                                  header.TextLabel.Font.PointSize);
                    var modifiedFont = String.Format("{0}{1}", htmlStyle, html);
                    header.TextLabel.AttributedText = new NSAttributedString(new NSString(modifiedFont).Encode(NSStringEncoding.Unicode, true), attr, ref nsError);
                }
                else
                {
                    var html      = String.Format(AppDelegate.LanguageBundle.GetLocalizedString("alerts_read"), "<b><font color='red'>" + alerts.Where(x => x.Read).Count().ToString() + "</font></b>");
                    var htmlStyle = string.Format("<style>body{{font-family:'{0}'; font-size:{1}px;}}</style>",
                                                  header.TextLabel.Font.FamilyName,
                                                  header.TextLabel.Font.PointSize);
                    var modifiedFont = String.Format("{0}{1}", htmlStyle, html);
                    header.TextLabel.AttributedText = new NSAttributedString(new NSString(modifiedFont).Encode(NSStringEncoding.Unicode, true), attr, ref nsError);
                }

                return(header);
            }
        private void UpdateText()
        {
            if (Control == null || Element == null)
            {
                return;
            }

            var isHtml = HtmlLabel.GetIsHtml(Element);

            if (!isHtml)
            {
                return;
            }


            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            var removeTags = HtmlLabel.GetRemoveHtmlTags(Element);

            var text = removeTags ?
                       HtmlToText.ConvertHtml(Control.Text) :
                       Element.Text;

            var helper = new LabelRendererHelper(Element, text);

            var htmlData = NSData.FromString(helper.ToString(), NSStringEncoding.Unicode);

            Control.AttributedText = new NSAttributedString(htmlData, attr, ref nsError);

            SetNeedsDisplay();
        }
Esempio n. 24
0
		protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName.Equals("Text") && Control != null)
			{
				// http://forums.xamarin.com/discussion/15530/nsattributedstringdocumentattributes-exception-on-ios-6

				NSParagraphStyle ps = NSParagraphStyle.Default;

				NSDictionary dict = new NSMutableDictionary() { {
						UIStringAttributeKey.Font,
						((ExtendedLabel)Element).Font.ToUIFont()
					},
				};

				var attr = new NSAttributedStringDocumentAttributes(dict);
				var nsError = new NSError();

				// This line announces, that content is html.
				attr.DocumentType = NSDocumentType.HTML;
				attr.StringEncoding = NSStringEncoding.UTF8;

				var html = ((ExtendedLabel)Element).TextExt + Environment.NewLine;

				NSString htmlString = new NSString(html); 
				NSData htmlData = htmlString.Encode(NSStringEncoding.UTF8); 

				NSAttributedString attrStr = new NSAttributedString(htmlData, attr, out dict, ref nsError);

				Control.AttributedText = attrStr;
				Control.SizeToFit();
				Control.SetNeedsLayout();

				Element.HeightRequest = Control.Bounds.Height;

				return;
			}

			if (e.PropertyName == "Height" || e.PropertyName == "Width")
			{
				// We calculate the correct height, because of the attributed string, Xamarin.Forms don't do it correct
				var width = (float)((ExtendedLabel)Element).Width;

				// Only do this, if we have a valid width
				if (width != -1)
				{
					var rect = Control.AttributedText.GetBoundingRect(new CoreGraphics.CGSize(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null);

					if (rect.Height != ((ExtendedLabel)Element).Height)
					{
						((ExtendedLabel)Element).HeightRequest = rect.Height;
					}
				}
			}

			base.OnElementPropertyChanged(sender, e);
		}
        private void SetHtmlText()
        {
            if (Control is UILabel label && Element is Label formLabel)
            {
                var documentAttributes = new NSAttributedStringDocumentAttributes();
                documentAttributes.DocumentType = NSDocumentType.HTML;
                var error = new NSError();

                label.AttributedText = new NSAttributedString(formLabel.Text, documentAttributes, ref error);
            }
        }
        public string FromHtml(string htmlFormat)
        {
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            var myHtmlData = NSData.FromString(htmlFormat, NSStringEncoding.Unicode);

            return(new NSAttributedString(myHtmlData, attr, ref nsError).Value);
        }
        private void SetHtmlText(string text)
        {
            var attr = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML
            };
            var nsError = new NSError();

            _textView.Editable          = false;
            _textView.AttributedText    = new NSAttributedString(text, attr, ref nsError);
            _textView.DataDetectorTypes = UIDataDetectorType.All;
        }
Esempio n. 28
0
        public static NSAttributedString GetHTMLFormattedText(string toBeFormatted, string fontFace = "HelveticaNeue", float fontSize = 5, string fontColor = "#757575", bool center = false)
        {
            NSError error         = null;
            var     formattedText = center ? $"<font face ='{fontFace}' size ={fontSize} color='{fontColor}'<center>{toBeFormatted}</center></font>"
                                       : $"<font face ='{fontFace}' size ={fontSize} color='{fontColor}'<justify>{toBeFormatted}</justify></font>";
            var attributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8
            };

            return(new NSAttributedString(formattedText, attributes, ref error));
        }
Esempio n. 29
0
        protected override void Bind()
        {
            base.Bind();

            NSError error = null;
            var     documentAttributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8
            };
            var attributedString = new NSAttributedString(Element.Html, documentAttributes, ref error);

            HtmlLabel.AttributedText = attributedString;
        }
Esempio n. 30
0
        private void CreateAttributedString(UILabel control, string html)
        {
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;
            // --------------
            // 02-01-2018 : Fix for default font family => https://github.com/matteobortolazzo/HtmlLabelPlugin/issues/9
            var fontDescriptor = control.Font.FontDescriptor.VisibleName;
            var fontFamily     = fontDescriptor.ToLower().Contains("system") ? "-apple-system,system-ui,BlinkMacSystemFont,Segoe UI" : control.Font.FamilyName;

            html += "<style> body{ font-family: " + fontFamily + ";}</style>";
            // --------------
            var myHtmlData = NSData.FromString(html, NSStringEncoding.Unicode);
            // control.Lines = 0;
            var mutable = new NSMutableAttributedString(new NSAttributedString(myHtmlData, attr, ref nsError));
            var links   = new List <LinkData>();

            control.AttributedText = mutable;

            // make a list of all links:
            mutable.EnumerateAttributes(new NSRange(0, mutable.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired, (NSDictionary attrs, NSRange range, ref bool stop) =>
            {
                foreach (var a in attrs) // should use attrs.ContainsKey(something) instead
                {
                    if (a.Key.ToString() != "NSLink")
                    {
                        continue;
                    }
                    links.Add(new LinkData(range, a.Value.ToString()));
                    return;
                }
            });

            // Set up a Gesture recognizer:
            if (links.Count <= 0)
            {
                return;
            }
            control.UserInteractionEnabled = true;
            var tapGesture = new UITapGestureRecognizer((tap) =>
            {
                var url = DetectTappedUrl(tap, (UILabel)tap.View, links);
                if (url != null)
                {
                    // open the link:
                    Device.OpenUri(new Uri(url));
                }
            });

            control.AddGestureRecognizer(tapGesture);
        }
Esempio n. 31
0
        public static string AttributedStringToHtml(NSAttributedString attributedString)
        {
            var range      = new NSRange(0, attributedString.Length);
            var dictionary = new NSAttributedStringDocumentAttributes();

            dictionary.DocumentType = NSDocumentType.HTML;
            NSError error      = new NSError();
            var     data       = attributedString.GetDataFromRange(range, dictionary, ref error);
            var     htmlString = new NSString(data, NSStringEncoding.UTF8);
            var     cleanHtml  = CleanHtml(htmlString);

            return(cleanHtml);
        }
        private void UpdateElement()
        {
            if (Control != null && Element != null && !string.IsNullOrWhiteSpace(Element.Text))
            {
                var attr    = new NSAttributedStringDocumentAttributes();
                var nsError = new NSError();
                attr.DocumentType = NSDocumentType.HTML;

                var myHtmlData = NSData.FromString(Element.Text, NSStringEncoding.Unicode);
                Control.Lines          = 0;
                Control.AttributedText = new NSAttributedString(myHtmlData, attr, ref nsError);
            }
        }
        public DetailViewController(RSSFeedItem item)
            : base(UITableViewStyle.Grouped, null, true)
        {
            var attributes = new NSAttributedStringDocumentAttributes();
              attributes.DocumentType = NSDocumentType.HTML;
              attributes.StringEncoding = NSStringEncoding.UTF8;
              var error = new NSError();
              var htmlString = new NSAttributedString(item.Description, attributes, ref error);

              Root = new RootElement(item.Title) {
                new Section{
                new StringElement(item.Author),
                new StringElement(item.PublishDate),
                        new StyledMultilineElement(htmlString),
                new HtmlElement("Full Article", item.Link)
              }
            };
        }
Esempio n. 34
0
        /// <summary>
        /// Converts HTML-formatted data to a string that contains the text content extracted from the HTML.
        /// </summary>
        /// <param name="html">A String containing HTML-formatted data.</param>
        /// <returns>A String of text content.</returns>
        public static string ConvertToText(string html)
        {
            // the platform implementations don't strip out unordered lists so we'll replace with bullet characters
            int i = 0;
            int i2;
            while (i > -1)
            {
                i = html.IndexOf("<li");
                if (i > -1)
                {
                    i2 = html.IndexOf(">", i);

                    if (i2 > -1)
                    {
                        html = html.Replace(html.Substring(i, (i2 - i) + 1), "<p>• ");
                    }
                }
            }

            i = 0;
            while (i > -1)
            {
                i = html.IndexOf("<ul");
                if (i > -1)
                {
                    i2 = html.IndexOf(">", i);

                    if (i2 > -1)
                    {
                        html = html.Replace(html.Substring(i, (i2 - i) + 1), "");
                    }
                }
            }

            i = 0;
            while (i > -1)
            {
                i = html.IndexOf("<img");
                if (i > -1)
                {
                    i2 = html.IndexOf(">", i);

                    if (i2 > -1)
                    {
                        html = html.Replace(html.Substring(i, (i2 - i) + 1), "");
                    }
                }
            }
            
            html = html.Replace("</ul>", "");
            html = html.Replace("</li>", "<p/>");

#if __ANDROID__
            ISpanned sp = Android.Text.Html.FromHtml(html);
            return sp.ToString().Trim();

#elif __IOS__ || __TVOS__
            byte[] data = global::System.Text.Encoding.UTF8.GetBytes(html);
            NSData d = NSData.FromArray(data);
            NSAttributedStringDocumentAttributes importParams = new NSAttributedStringDocumentAttributes();
            importParams.DocumentType = NSDocumentType.HTML;
            NSError error = new NSError();
            error = null;
            NSDictionary dict = new NSDictionary();

            var attrString = new NSAttributedString(d, importParams, out dict, ref error);
            return attrString.Value;

#elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81
            return Windows.Data.Html.HtmlUtilities.ConvertToText(html);
#elif WINDOWS_PHONE || WIN32
            return global::System.Net.WebUtility.HtmlDecode(Regex.Replace(html, "<(.|\n)*?>", ""));
#else
            throw new global::System.PlatformNotSupportedException();
#endif
        }