Beispiel #1
0
 public NSAttributedString(string str,
                           NSFont font                         = null,
                           NSColor foregroundColor             = null,
                           NSColor backgroundColor             = null,
                           NSColor strokeColor                 = null,
                           NSColor underlineColor              = null,
                           NSColor strikethroughColor          = null,
                           NSUnderlineStyle underlineStyle     = NSUnderlineStyle.None,
                           NSUnderlineStyle strikethroughStyle = NSUnderlineStyle.None,
                           NSParagraphStyle paragraphStyle     = null,
                           float strokeWidth                   = 0,
                           NSShadow shadow                     = null,
                           NSUrl link                  = null,
                           bool superscript            = false,
                           NSTextAttachment attachment = null,
                           NSLigatureType ligature     = NSLigatureType.Default,
                           float baselineOffset        = 0,
                           float kerningAdjustment     = 0,
                           float obliqueness           = 0,
                           float expansion             = 0,
                           NSCursor cursor             = null,
                           string toolTip              = null,
                           int characterShape          = 0,
                           NSGlyphInfo glyphInfo       = null,
                           NSArray writingDirection    = null,
                           bool markedClauseSegment    = false,
                           NSTextLayoutOrientation verticalGlyphForm = NSTextLayoutOrientation.Horizontal,
                           NSTextAlternatives textAlternatives       = null,
                           NSSpellingState spellingState             = NSSpellingState.None) : this(str, NSStringAttributes.ToDictionary(
                                                                                                        font : font,
                                                                                                        foregroundColor : foregroundColor,
                                                                                                        backgroundColor : backgroundColor,
                                                                                                        strokeColor : strokeColor,
                                                                                                        underlineColor : underlineColor,
                                                                                                        strikethroughColor : strikethroughColor,
                                                                                                        underlineStyle : underlineStyle,
                                                                                                        strikethroughStyle : strikethroughStyle,
                                                                                                        paragraphStyle : paragraphStyle,
                                                                                                        strokeWidth : strokeWidth,
                                                                                                        shadow : shadow,
                                                                                                        link : link,
                                                                                                        superscript : superscript,
                                                                                                        attachment : attachment,
                                                                                                        ligature : ligature,
                                                                                                        baselineOffset : baselineOffset,
                                                                                                        kerningAdjustment : kerningAdjustment,
                                                                                                        obliqueness : obliqueness,
                                                                                                        expansion : expansion,
                                                                                                        cursor : cursor,
                                                                                                        toolTip : toolTip,
                                                                                                        characterShape : characterShape,
                                                                                                        glyphInfo : glyphInfo,
                                                                                                        writingDirection : writingDirection,
                                                                                                        markedClauseSegment : markedClauseSegment,
                                                                                                        verticalGlyphForm : verticalGlyphForm,
                                                                                                        textAlternatives : textAlternatives,
                                                                                                        spellingState : spellingState
                                                                                                        ))
 {
 }
Beispiel #2
0
        public void RetainCount_7()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("Requires iOS 7+");
            }

            var sa = new UIStringAttributes();

            sa.Expansion = 0.0f;

            var uc = UIColor.FromRGBA(0.1f, 0.2f, 0.3f, 0.4f);

            Assert.That(uc.RetainCount, Is.EqualTo((nint)2), "UnderlineColor-new");
            sa.UnderlineColor = uc;
            Assert.That(uc.RetainCount, Is.EqualTo((nint)3), "UnderlineColor-set");

            var sc = UIColor.FromRGBA(0.5f, 0.6f, 0.7f, 0.8f);

            Assert.That(sc.RetainCount, Is.EqualTo((nint)2), "StrikethroughColor-new");
            sa.StrikethroughColor = sc;
            Assert.That(sc.RetainCount, Is.EqualTo((nint)3), "StrikethroughColor-set");

            var u = new NSUrl("http://xamarin.com");

            Assert.That(u.RetainCount, Is.EqualTo((nint)1), "Link-new");
            sa.Link = u;
            Assert.That(u.RetainCount, Is.EqualTo((nint)2), "Link-set");

#if !__WATCHOS__
            var ta = new NSTextAttachment();
            Assert.That(ta.RetainCount, Is.EqualTo((nint)1), "TextAttachment-new");
            sa.TextAttachment = ta;
            Assert.That(ta.RetainCount, Is.EqualTo((nint)2), "TextAttachment-set");
#endif // !__WATCHOS__

            for (int i = 0; i < 16; i++)
            {
                Assert.NotNull(sa.UnderlineColor, "UnderlineColor-get");
                Assert.NotNull(sa.StrikethroughColor, "StrikethroughColor-get");
                Assert.NotNull(sa.Link, "Link-get");
#if !__WATCHOS__
                Assert.NotNull(sa.TextAttachment, "TextAttachment-get");
#endif
            }

            Assert.That(sa.UnderlineColor.RetainCount, Is.EqualTo((nint)3), "UnderlineColor");
            Assert.That(sa.StrikethroughColor.RetainCount, Is.EqualTo((nint)3), "StrikethroughColor");
            Assert.That(sa.Link.RetainCount, Is.EqualTo((nint)2), "Link");
#if !__WATCHOS__
            Assert.That(sa.TextAttachment.RetainCount, Is.EqualTo((nint)2), "TextAttachment");
#endif

            GC.KeepAlive(uc);
            GC.KeepAlive(sc);
            GC.KeepAlive(u);
#if !__WATCHOS__
            GC.KeepAlive(ta);
#endif
        }
Beispiel #3
0
        public static NSMutableAttributedString GetAttachmentString(
            this string imageName,
            double fontCapHeight,
            UIImageRenderingMode renderingMode = UIImageRenderingMode.AlwaysTemplate)
        {
            var attachment = new NSTextAttachment
            {
                Image = UIImage
                        .FromBundle(imageName)
                        .ImageWithRenderingMode(renderingMode)
            };

            var imageSize = attachment.Image.Size;
            var y         = (fontCapHeight - imageSize.Height) / 2;

            attachment.Bounds = new CGRect(0, y, imageSize.Width, imageSize.Height);

            //There neeeds to be a space before the dot, otherwise the colors don't work
            var result = new NSMutableAttributedString(" ");

            result.AddAttribute(UIStringAttributeKey.Font, UIFont.SystemFontOfSize(0), new NSRange(0, 1));

            var attachmentString = NSAttributedString.FromAttachment(attachment);

            result.Append(attachmentString);

            return(result);
        }
Beispiel #4
0
        public static NSMutableAttributedString GetAttachmentString(
            this string imageName,
            double fontCapHeight,
            UIImageRenderingMode renderingMode = UIImageRenderingMode.AlwaysTemplate)
        {
            var attachment = new NSTextAttachment
            {
                Image = UIImage
                        .FromBundle(imageName)
                        .ImageWithRenderingMode(renderingMode)
            };

            var imageSize = attachment.Image.Size;
            var y         = (fontCapHeight - imageSize.Height) / 2;

            attachment.Bounds = new CGRect(0, y, imageSize.Width, imageSize.Height);

            var result = new NSMutableAttributedString("");

            if (!UIDevice.CurrentDevice.CheckSystemVersion(13, 0))
            {
                // For older iOS versions, there neeeds to be a space before the dot, otherwise the colors don't work
                // in iOS 13, they fixed it and this hack breaks the colors
                result.Append(new NSAttributedString(" "));
                result.AddAttribute(UIStringAttributeKey.Font, UIFont.SystemFontOfSize(0), new NSRange(0, 1));
            }

            var attachmentString = NSAttributedString.FromAttachment(attachment);

            result.Append(attachmentString);

            return(result);
        }
        public void UIKitAttachmentConveniences_New()
        {
            TestRuntime.AssertSystemVersion(PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);
            TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 11, throwIfOtherPlatform: false);

            // so we added custom code calling the (old) category helper - but we had to pick a different name
            using (var ta = new NSTextAttachment(null, null))
                using (var as2 = NSAttributedString.FromAttachment(ta)) {
                    Assert.That(as2.Length, Is.EqualTo((nint)1), "Length");
                    Assert.That(as2.Value [0], Is.EqualTo((char)0xFFFC), "NSAttachmentCharacter");
                }
        }
Beispiel #6
0
        public void CtorNull()
        {
            TestRuntime.AssertSystemVersion(PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);

            using (var ta = new NSTextAttachment(null, null)) {
                Assert.IsTrue(ta.Bounds.IsEmpty, "Bounds");
                Assert.Null(ta.Contents, "Contents");
                Assert.Null(ta.FileType, "FileType");
                Assert.Null(ta.FileWrapper, "FileWrapper");
                Assert.Null(ta.Image, "Image");
            }
        }
        private NSAttributedString buildString(string project, string task, string client, UIColor color, bool isTaskPlaceholder)
        {
            var builder   = new StringBuilder();
            var hasClient = !string.IsNullOrEmpty(client);

            if (!string.IsNullOrEmpty(project))
            {
                builder.Append($" {project}");
            }

            if (!string.IsNullOrEmpty(task) && !isTaskPlaceholder)
            {
                builder.Append($": {task}");
            }

            if (hasClient)
            {
                builder.Append($" {client}");
            }

            var text = builder.ToString();

            var result      = new NSMutableAttributedString(text);
            var clientIndex = text.Length - (client?.Length ?? 0);

            var projectNameRange      = new NSRange(0, clientIndex);
            var projectNameAttributes = new UIStringAttributes {
                ForegroundColor = color
            };

            result.AddAttributes(projectNameAttributes, projectNameRange);

            if (hasClient)
            {
                var clientNameRange      = new NSRange(clientIndex, client.Length);
                var clientNameAttributes = new UIStringAttributes {
                    ForegroundColor = clientColor
                };
                result.AddAttributes(clientNameAttributes, clientNameRange);
            }

            if (isTaskPlaceholder)
            {
                var attachment = new NSTextAttachment();
                attachment.Image = placeHolderImage();
                var placeholderImage = new NSMutableAttributedString(" ");
                placeholderImage.Append(NSAttributedString.FromAttachment(attachment));
                result.Append(placeholderImage);
                return(result);
            }

            return(result);
        }
Beispiel #8
0
        public void UIKitAttachmentConveniences_New()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("requires iOS7+");
            }

            // so we added custom code calling the (old) category helper - but we had to pick a different name
            using (var ta = new NSTextAttachment(null, null))
                using (var as2 = NSAttributedString.FromAttachment(ta)) {
                    Assert.That(as2.Length, Is.EqualTo((nint)1), "Length");
                    Assert.That(as2.Value [0], Is.EqualTo((char)0xFFFC), "NSAttachmentCharacter");
                }
        }
        private void ConfigureTextView()
        {
            TextView.Font = UIFont.FromDescriptor(UIFontDescriptor.PreferredBody, 0);

            TextView.TextColor       = UIColor.Black;
            TextView.BackgroundColor = UIColor.White;
            TextView.ScrollEnabled   = true;

            // Let's modify some of the attributes of the attributed string.
            // You can modify these attributes yourself to get a better feel for what they do.
            // Note that the initial text is visible in the storyboard.
            var attributedText = new NSMutableAttributedString(TextView.AttributedText);

            // Use NSString so the result of rangeOfString is an NSRange, not Range<String.Index>.
            NSString text = (NSString)TextView.Text;

            // Find the range of each element to modify.
            var boldRange        = CalcRangeFor(text, "bold".Localize());
            var highlightedRange = CalcRangeFor(text, "highlighted".Localize());
            var underlinedRange  = CalcRangeFor(text, "underlined".Localize());
            var tintedRange      = CalcRangeFor(text, "tinted".Localize());

            // Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait.
            var boldFontDescriptor = TextView.Font.FontDescriptor.CreateWithTraits(UIFontDescriptorSymbolicTraits.Bold);
            var boldFont           = UIFont.FromDescriptor(boldFontDescriptor, 0);

            attributedText.AddAttribute(UIStringAttributeKey.Font, value: boldFont, range: boldRange);

            // Add highlight.
            attributedText.AddAttribute(UIStringAttributeKey.BackgroundColor, value: ApplicationColors.Green, range: highlightedRange);

            // Add underline.
            attributedText.AddAttribute(UIStringAttributeKey.UnderlineStyle, value: NSNumber.FromInt32((int)NSUnderlineStyle.Single), range: underlinedRange);

            // Add tint.
            attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, value: ApplicationColors.Blue, range: tintedRange);

            // Add image attachment.
            var img            = UIImage.FromBundle("text_view_attachment");
            var textAttachment = new NSTextAttachment {
                Image  = img,
                Bounds = new CGRect(PointF.Empty, img.Size),
            };

            var textAttachmentString = NSAttributedString.CreateFrom(textAttachment);

            attributedText.Append(textAttachmentString);

            TextView.AttributedText = attributedText;
        }
Beispiel #10
0
        public override void LoadView()
        {
            View = new UIView(UIScreen.MainScreen.Bounds)
            {
                BackgroundColor = UIColor.GroupTableViewBackgroundColor
            };

            var height = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? 450 : 300;

            Calendar = new FSCalendar()
            {
                Frame                   = new CGRect(0, NavigationController.NavigationBar.Frame.GetMaxY(), View.Frame.Width, height),
                DataSource              = this,
                WeakDelegate            = this,
                AllowsMultipleSelection = true
            };
            Calendar.SwipeToChooseGesture.Enabled = true;
            View.AddSubview(Calendar);

            Calendar.CalendarHeaderView.BackgroundColor  = UIColor.LightGray.ColorWithAlpha(0.1f);
            Calendar.CalendarWeekdayView.BackgroundColor = UIColor.LightGray.ColorWithAlpha(0.1f);
            Calendar.FSAppearance.EventSelectionColor    = UIColor.White;
            Calendar.FSAppearance.EventOffset            = new CGPoint(0, -7);
            Calendar.Today = null; // Hide the today circle
            Calendar.RegisterClass(new ObjCRuntime.Class(typeof(DIYCalendarCell)), "cell");
            var scopeGesture = new UIPanGestureRecognizer((UIPanGestureRecognizer obj) => {
                Calendar.HandleScopeGesture(obj);
            });

            Calendar.AddGestureRecognizer(scopeGesture);

            EventLabel = new UILabel(new CGRect(0, Calendar.Frame.GetMaxY() + 10, View.Frame.Width, 50))
            {
                TextAlignment = UITextAlignment.Center,
                Font          = UIFont.GetPreferredFontForTextStyle(UIFontTextStyle.Subheadline)
            };
            View.AddSubview(EventLabel);

            var attributedText = new NSMutableAttributedString("");
            var attatchment    = new NSTextAttachment()
            {
                Image = UIImage.FromBundle("icon_cat")
            };

            attatchment.Bounds = new CGRect(0, -3, attatchment.Image.Size.Width, attatchment.Image.Size.Height);
            attributedText.Append(NSAttributedString.FromAttachment(attatchment));
            attributedText.Append(new NSAttributedString(" This is a daily event "));
            attributedText.Append(NSAttributedString.FromAttachment(attatchment));
            EventLabel.AttributedText = attributedText;
        }
        public void CtorNull()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("requires iOS7+");
            }

            using (var ta = new NSTextAttachment(null, null)) {
                Assert.IsTrue(ta.Bounds.IsEmpty, "Bounds");
                Assert.Null(ta.Contents, "Contents");
                Assert.Null(ta.FileType, "FileType");
                Assert.Null(ta.FileWrapper, "FileWrapper");
                Assert.Null(ta.Image, "Image");
            }
        }
Beispiel #12
0
        private void SetupStatusDisplayTextField()
        {
            NSTextAttachment attachment = new NSTextAttachment
            {
                Image  = NSImage.ImageNamed(NSImageName.ApplicationIcon),
                Bounds = CoreGraphics.CGRect.FromLTRB(0, -4, 14, 10),
            };
            NSAttributedString imageAttributedString = NSAttributedString.FromAttachment(attachment);

            NSMutableAttributedString statusDisplayAttributedString = new NSMutableAttributedString();

            statusDisplayAttributedString.Append(imageAttributedString);
            statusDisplayAttributedString.Append(new NSAttributedString("  Apple Cider 2020 for Mac"));

            StatusDisplayTextField.AttributedStringValue = statusDisplayAttributedString;
        }
Beispiel #13
0
        public void UIKitAttachmentConveniences_Old()
        {
            if (!TestRuntime.CheckSystemAndSDKVersion(7, 0))
            {
                Assert.Inconclusive("requires iOS7+");
            }

            NSAttributedString as1 = null;

            // it's weird looking to use an instance (even null) so you can call a *static* category method...
            using (var ta = new NSTextAttachment(null, null))
                using (var as2 = as1.FromTextAttachment(ta)) {
                    Assert.That(as2.Length, Is.EqualTo((nint)1), "Length");
                    Assert.That(as2.Value [0], Is.EqualTo((char)0xFFFC), "NSAttachmentCharacter");
                }
        }
Beispiel #14
0
        private void Initialize()
        {
            var attachment = new NSTextAttachment {
                Image  = Image,
                Bounds = new CGRect(-Insets.Left, ImageYPosition, ImageSize.Height, ImageSize.Width)
            };

            var newText = new NSMutableAttributedString();

            newText.Append(NSAttributedString.CreateFrom(attachment));

            NSAttributedString labelText = new NSAttributedString(Text ?? " ");

            newText.Append(labelText);

            AttributedText = newText;
        }
Beispiel #15
0
        /// <summary>
        /// 插入图片到textView
        /// </summary>
        /// <param name="bytes">Stream.</param>
        private void AddImageToTextView(byte[] bytes, string originSizeUrl)
        {
            this.InvokeOnMainThread(() =>
            {
                using (var stream = new MemoryStream(bytes))
                {
                    ImageCell cell = new ImageCell(NSImage.FromStream(stream));
                    cell.SetData("picUrl", originSizeUrl);

                    NSTextAttachment am = new NSTextAttachment
                    {
                        AttachmentCell = cell
                    };
                    NSAttributedString nbs = NSAttributedString.FromAttachment(am);
                    this.TextPrint.TextStorage.Append(nbs);
                }
            });
        }
        public NSAttributedString Convert(string project, string task, string client, UIColor color, bool isProjectPlaceholder = false, bool isTaskPlaceholder = false)
        {
            if (isProjectPlaceholder)
            {
                var attachment = new NSTextAttachment();
                attachment.Image = placeHolderImage();
                var placeholderImage = NSAttributedString.FromAttachment(attachment);
                return(placeholderImage);
            }

            var dotString    = projectDotImageResource.GetAttachmentString(fontHeight);
            var clone        = new NSMutableAttributedString(dotString);
            var dottedString = tryAddColorToDot(clone, color);
            var projectInfo  = buildString(project, task, client, color, isTaskPlaceholder);

            dottedString.Append(projectInfo);

            return(dottedString);
        }
Beispiel #17
0
        public void SetTexts(string mainText, string moreText, string showMoreText, UIImage showMoreImage)
        {
            var text = mainText;

            if (moreText.Length > 0)
            {
                text += "\n\n" + moreText;
            }
            TextLabel.Text = text;

            var attributed = new NSMutableAttributedString(showMoreText + " ");
            var attachment = new NSTextAttachment {
                Image = showMoreImage
            };

            attributed.Append(NSAttributedString.FromAttachment(attachment));

            PerformWithoutAnimation(() =>
            {
                ShowMoreButton.SetAttributedTitle(attributed, UIControlState.Normal);
                ShowMoreButton.LayoutIfNeeded();
            });
        }
Beispiel #18
0
 // This is a [Category] -> C# extension method (see uikit.cs) but it targets on static selector
 // the resulting syntax does not look good in user code so we provide a better looking API
 // https://bugzilla.xamarin.com/show_bug.cgi?id=15268
 // https://trello.com/c/iQpXOxCd/227-category-and-static-methods-selectors
 // note: we cannot reuse the same method name - as it would break compilation of existing apps
 public static NSAttributedString CreateFrom(NSTextAttachment attachment)
 {
     return (null as NSAttributedString).FromTextAttachment (attachment);
 }
        private void ConfigureTextView()
        {
            textView.Font = UIFont.FromDescriptor(UIFontDescriptor.PreferredBody, 0);

            textView.TextColor       = UIColor.Black;
            textView.BackgroundColor = UIColor.White;
            textView.ScrollEnabled   = true;

            // Let's modify some of the attributes of the attributed string.
            // You can modify these attributes yourself to get a better feel for what they do.
            // Note that the initial text is visible in the storyboard.
            var attributedText = new NSMutableAttributedString(textView.AttributedText);

            // Find the range of each element to modify.
            var text             = textView.Text;
            var boldRange        = GetRangeFor(text, "bold");
            var highlightedRange = GetRangeFor(text, "highlighted");
            var underlinedRange  = GetRangeFor(text, "underlined");
            var tintedRange      = GetRangeFor(text, "tinted");

            // Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait.
            var boldFontDescriptor = textView.Font.FontDescriptor.CreateWithTraits(UIFontDescriptorSymbolicTraits.Bold);
            var boldFont           = UIFont.FromDescriptor(boldFontDescriptor, 0);

            attributedText.AddAttribute(UIStringAttributeKey.Font, boldFont, boldRange);

            // Add highlight.
            attributedText.AddAttribute(UIStringAttributeKey.BackgroundColor, UIColor.Green, highlightedRange);

            // Add underline.
            attributedText.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), underlinedRange);

            // Add tint.
            attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Blue, tintedRange);

            // Add image attachment.
            var image          = UIImage.FromBundle("text_view_attachment");
            var textAttachment = new NSTextAttachment
            {
                Image  = image,
                Bounds = new CGRect(PointF.Empty, image.Size),
            };

            var textAttachmentString = NSAttributedString.CreateFrom(textAttachment);

            attributedText.Append(new NSAttributedString(Environment.NewLine));
            attributedText.Append(textAttachmentString);

            textView.AttributedText = attributedText;

            image.Dispose();
            attributedText.Dispose();
            image          = null;
            attributedText = null;

            NSRange GetRangeFor(string source, string substring)
            {
                return(new NSRange
                {
                    Location = source.IndexOf(substring, StringComparison.OrdinalIgnoreCase),
                    Length = substring.Length
                });
            }
        }
		private void ConfigureTextView()
		{
			TextView.Font = UIFont.FromDescriptor (UIFontDescriptor.PreferredBody, 0);

			TextView.TextColor = UIColor.Black;
			TextView.BackgroundColor = UIColor.White;
			TextView.ScrollEnabled = true;

			// Let's modify some of the attributes of the attributed string.
			// You can modify these attributes yourself to get a better feel for what they do.
			// Note that the initial text is visible in the storyboard.
			var attributedText = new NSMutableAttributedString (TextView.AttributedText);

			// Use NSString so the result of rangeOfString is an NSRange, not Range<String.Index>.
			NSString text = (NSString)TextView.Text;

			// Find the range of each element to modify.
			var boldRange = CalcRangeFor (text, "bold".Localize ());
			var highlightedRange = CalcRangeFor (text, "highlighted".Localize ());
			var underlinedRange = CalcRangeFor (text, "underlined".Localize ());
			var tintedRange = CalcRangeFor (text, "tinted".Localize ());

			// Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait.
			var boldFontDescriptor = TextView.Font.FontDescriptor.CreateWithTraits (UIFontDescriptorSymbolicTraits.Bold);
			var boldFont = UIFont.FromDescriptor (boldFontDescriptor, 0);
			attributedText.AddAttribute (UIStringAttributeKey.Font, value: boldFont, range: boldRange);

			// Add highlight.
			attributedText.AddAttribute (UIStringAttributeKey.BackgroundColor, value: ApplicationColors.Green, range: highlightedRange);

			// Add underline.
			attributedText.AddAttribute (UIStringAttributeKey.UnderlineStyle, value: NSNumber.FromInt32 ((int)NSUnderlineStyle.Single), range: underlinedRange);

			// Add tint.
			attributedText.AddAttribute (UIStringAttributeKey.ForegroundColor, value: ApplicationColors.Blue, range: tintedRange);

			// Add image attachment.
			var img = UIImage.FromBundle ("text_view_attachment");
			var textAttachment = new NSTextAttachment {
				Image = img,
				Bounds = new CGRect(PointF.Empty, img.Size),
			};

			var textAttachmentString = NSAttributedString.CreateFrom (textAttachment);
			attributedText.Append (textAttachmentString);

			TextView.AttributedText = attributedText;
		}
        static internal NSDictionary ToDictionary(
            NSFont font,
            NSColor foregroundColor,
            NSColor backgroundColor,
            NSColor strokeColor,
            NSColor underlineColor,
            NSColor strikethroughColor,
            NSUnderlineStyle underlineStyle,
            NSUnderlineStyle strikethroughStyle,
            NSParagraphStyle paragraphStyle,
            float strokeWidth,
            NSShadow shadow,
            NSUrl link,
            bool superscript,
            NSTextAttachment attachment,
            NSLigatureType ligature,
            float baselineOffset,
            float kerningAdjustment,
            float obliqueness,
            float expansion,
            NSCursor cursor,
            string toolTip,
            int characterShape,
            NSGlyphInfo glyphInfo,
            NSArray writingDirection,
            bool markedClauseSegment,
            NSTextLayoutOrientation verticalGlyphForm,
            NSTextAlternatives textAlternatives,
            NSSpellingState spellingState)
        {
            var attr = new NSStringAttributes();

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

            if (paragraphStyle != null)
            {
                attr.ParagraphStyle = paragraphStyle;
            }

            if (foregroundColor != null)
            {
                attr.ForegroundColor = foregroundColor;
            }

            if (underlineStyle != NSUnderlineStyle.None)
            {
                attr.UnderlineStyle = (int?)underlineStyle;
            }

            if (superscript)
            {
                attr.Superscript = true;
            }

            if (backgroundColor != null)
            {
                attr.BackgroundColor = backgroundColor;
            }

            if (attachment != null)
            {
                attr.Attachment = attachment;
            }

            if (ligature != NSLigatureType.Default)
            {
                attr.Ligature = ligature;
            }

            if (baselineOffset != 0)
            {
                attr.BaselineOffset = baselineOffset;
            }

            if (kerningAdjustment != 0)
            {
                attr.KerningAdjustment = kerningAdjustment;
            }

            if (link != null)
            {
                attr.Link = link;
            }

            if (strokeWidth != 0)
            {
                attr.StrokeWidth = strokeWidth;
            }

            if (strokeColor != null)
            {
                attr.StrokeColor = strokeColor;
            }

            if (underlineColor != null)
            {
                attr.UnderlineColor = underlineColor;
            }

            if (strikethroughStyle != NSUnderlineStyle.None)
            {
                attr.StrikethroughStyle = (int?)strikethroughStyle;
            }

            if (strikethroughColor != null)
            {
                attr.StrikethroughColor = strikethroughColor;
            }

            if (shadow != null)
            {
                attr.Shadow = shadow;
            }

            if (obliqueness != 0)
            {
                attr.Obliqueness = obliqueness;
            }

            if (expansion != 0)
            {
                attr.Expansion = expansion;
            }

            if (cursor != null)
            {
                attr.Cursor = cursor;
            }

            if (toolTip != null)
            {
                attr.ToolTip = toolTip;
            }

            if (characterShape != 0)
            {
                attr.CharacterShape = 0;
            }

            if (glyphInfo != null)
            {
                attr.GlyphInfo = glyphInfo;
            }

            if (writingDirection != null)
            {
                attr.WritingDirection = writingDirection;
            }

            if (markedClauseSegment)
            {
                attr.MarkedClauseSegment = true;
            }

            if (verticalGlyphForm != NSTextLayoutOrientation.Horizontal)
            {
                attr.VerticalGlyphForm = verticalGlyphForm;
            }

            if (textAlternatives != null)
            {
                attr.TextAlternatives = textAlternatives;
            }

            if (spellingState != NSSpellingState.None)
            {
                attr.SpellingState = spellingState;
            }

            var dict = attr.Dictionary;

            return(dict.Count == 0 ? null : dict);
        }
        public static NSAttributedString AttributedStringForTextComponents(ICollection <TextComponent> textComponents, bool usePrimaryColor)
        {
            var attributedString   = new NSMutableAttributedString();
            var font               = UIFont.SystemFontOfSize(15);
            var primaryTextColor   = usePrimaryColor ? Color.PRIMARY_TEXT_COLOR.ToUIColor() : Color.SECONDARY_TEXT_COLOR.ToUIColor();
            var secondaryTextColor = Color.SECONDARY_TEXT_COLOR.ToUIColor();

            foreach (var component in textComponents)
            {
                if (component.PrimaryText != null)
                {
                    var translatedText = NSBundle.MainBundle.LocalizedString(component.PrimaryText, "");
                    attributedString.Append(new NSAttributedString(translatedText, foregroundColor: primaryTextColor, font: font));
                }
                else if (component.SecondaryText != null)
                {
                    var translatedText = NSBundle.MainBundle.LocalizedString(component.SecondaryText, "");
                    attributedString.Append(new NSAttributedString(translatedText, foregroundColor: secondaryTextColor, font: font));
                }
                else if (component.IconIdentifier != TextComponent.Icon.None)
                {
                    string icon = "info";
                    switch (component.IconIdentifier)
                    {
                    case TextComponent.Icon.Info:
                        icon = "info";
                        break;

                    case TextComponent.Icon.Location:
                        icon = "location";
                        break;

                    case TextComponent.Icon.Person:
                        icon = "person";
                        break;

                    case TextComponent.Icon.Subject:
                        icon = "book";
                        break;
                    }

                    var iconImage      = UIImage.FromBundle(icon);
                    var iconAttachment = new NSTextAttachment
                    {
                        Image  = iconImage,
                        Bounds = new CoreGraphics.CGRect(new CoreGraphics.CGPoint(0, font.Descender), iconImage.Size),
                    };

                    var attributedIconString = NSAttributedString.FromAttachment(iconAttachment);

                    // Fix for text attachment tinting bug https://stackoverflow.com/a/36319475/1668608
                    attributedString.Append(new NSAttributedString(" ", UIFont.SystemFontOfSize(0)));

                    attributedString.Append(attributedIconString);
                    attributedString.AddAttributes(new UIStringAttributes {
                        ForegroundColor = secondaryTextColor
                    },
                                                   new NSRange(attributedString.Length - attributedIconString.Length - 1, attributedIconString.Length + 1));

                    attributedString.Append(new NSAttributedString(" ", font));
                }
            }

            var paragraphStyle = new NSMutableParagraphStyle
            {
                ParagraphSpacing = 0.25F * font.LineHeight
            };

            attributedString.AddAttributes(new UIStringAttributes {
                ParagraphStyle = paragraphStyle
            },
                                           new NSRange(0, attributedString.Length - 1));

            return(attributedString);
        }
Beispiel #23
0
 // This is a [Category] -> C# extension method (see uikit.cs) but it targets on static selector
 // the resulting syntax does not look good in user code so we provide a better looking API
 // https://bugzilla.xamarin.com/show_bug.cgi?id=15268
 // https://trello.com/c/iQpXOxCd/227-category-and-static-methods-selectors
 // note: we cannot reuse the same method name - as it would break compilation of existing apps
 public static NSAttributedString CreateFrom(NSTextAttachment attachment)
 {
     return((null as NSAttributedString).FromTextAttachment(attachment));
 }
Beispiel #24
0
        public NSAttributedString(string str,
            NSFont font = null,
            NSColor foregroundColor = null,
            NSColor backgroundColor = null,
            NSColor strokeColor = null,
            NSColor underlineColor = null,
            NSColor strikethroughColor = null,
            NSUnderlineStyle underlineStyle = NSUnderlineStyle.None,
            NSUnderlineStyle strikethroughStyle = NSUnderlineStyle.None,
            NSParagraphStyle paragraphStyle = null,
            float strokeWidth = 0,
            NSShadow shadow = null,
            NSUrl link = null,
            bool superscript = false,
            NSTextAttachment attachment = null,
            NSLigatureType ligature = NSLigatureType.Default,
            float baselineOffset = 0,
            float kerningAdjustment = 0,
            float obliqueness = 0,
            float expansion = 0,
            NSCursor cursor = null,
            string toolTip = null,
            int characterShape = 0,
            NSGlyphInfo glyphInfo = null,
            NSArray writingDirection = null,
            bool markedClauseSegment = false,
            NSTextLayoutOrientation verticalGlyphForm = NSTextLayoutOrientation.Horizontal,
            NSTextAlternatives textAlternatives = null,
            NSSpellingState spellingState = NSSpellingState.None)
            : this(str, NSStringAttributes.ToDictionary (
				font: font,
				foregroundColor: foregroundColor,
				backgroundColor: backgroundColor,
				strokeColor: strokeColor,
				underlineColor: underlineColor,
				strikethroughColor: strikethroughColor,
				underlineStyle: underlineStyle,
				strikethroughStyle: strikethroughStyle,
				paragraphStyle: paragraphStyle,
				strokeWidth: strokeWidth,
				shadow: shadow,
				link: link,
				superscript: superscript,
				attachment: attachment,
				ligature: ligature,
				baselineOffset: baselineOffset,
				kerningAdjustment: kerningAdjustment,
				obliqueness: obliqueness,
				expansion: expansion,
				cursor: cursor,
				toolTip: toolTip,
				characterShape: characterShape,
				glyphInfo: glyphInfo,
				writingDirection: writingDirection,
				markedClauseSegment: markedClauseSegment,
				verticalGlyphForm: verticalGlyphForm,
				textAlternatives: textAlternatives,
				spellingState: spellingState
			))
        {
        }