private int GetCharacterIndexAtPoint(Point point) { if (!_drawRect.Contains(point)) { return(-1); } // Configure textContainer var textContainer = new NSTextContainer(); textContainer.LineFragmentPadding = 0; textContainer.LineBreakMode = LineBreakMode; textContainer.MaximumNumberOfLines = (nuint)Lines; textContainer.Size = _drawRect.Size; // Configure layoutManager var layoutManager = new NSLayoutManager(); layoutManager.AddTextContainer(textContainer); // Configure textStorage var textStorage = new NSTextStorage(); textStorage.SetString(AttributedText); textStorage.AddLayoutManager(layoutManager); textStorage.SetAttributes( new UIStringAttributes() { Font = Font }, new NSRange(0, textStorage.Length) ); // Find the tapped character's index var partialFraction = (nfloat)0; var pointInTextContainer = new CGPoint(point.X - _drawRect.X, point.Y - _drawRect.Y); var characterIndex = (int)layoutManager.CharacterIndexForPoint(pointInTextContainer, textContainer, ref partialFraction); return(characterIndex); }
void ResetAttributes(NSColor foregroundColorOverride = null) { // clear user attributes TextStorage.SetAttributes(new NSDictionary(), new NSRange(0, TextStorage.Length)); var r = new NSRange(0, Text.Length); TextStorage.SetString(new NSAttributedString(Text)); TextStorage.SetAlignment(TextAlignment.ToNSTextAlignment(), r); if (Font != null) { // set a global font TextStorage.AddAttribute(NSStringAttributeKey.Font, Font, r); } // paragraph style TextContainer.LineBreakMode = TextTrimming == TextTrimming.WordElipsis ? NSLineBreakMode.TruncatingTail : NSLineBreakMode.ByWordWrapping; var pstyle = NSParagraphStyle.DefaultParagraphStyle.MutableCopy() as NSMutableParagraphStyle; pstyle.Alignment = TextAlignment.ToNSTextAlignment(); if (TextTrimming == TextTrimming.WordElipsis) { pstyle.LineBreakMode = NSLineBreakMode.TruncatingTail; } TextStorage.AddAttribute(NSStringAttributeKey.ParagraphStyle, pstyle, r); // set foreground color override if (foregroundColorOverride != null) { TextStorage.AddAttribute(NSStringAttributeKey.ForegroundColor, foregroundColorOverride, r); } // restore user attributes foreach (var att in Attributes) { AddAttributeInternal(att); } }