public override void ViewDidLoad() { base.ViewDidLoad(); var me = RealmUserServices.GetMe(true); var initials = (me.FirstName?.FirstOrDefault() + " " + me.LastName?.FirstOrDefault()).Trim(); CTStringAttributes attributes = new CTStringAttributes(); attributes.KerningAdjustment = -2; NSAttributedString attributedString = new NSAttributedString(initials, attributes); InititalsLabel.AttributedText = attributedString; InititalsLabel.BackgroundColor = UIColor.FromWhiteAlpha(0.9f, 1); InititalsLabel.TextColor = UIColor.Gray; InititalsLabel.Layer.MasksToBounds = true; InititalsLabel.Layer.CornerRadius = InititalsLabel.Frame.Size.Width / 2; NameLabel.Text = me.FirstName + " " + me.LastName; HandleLabel.Text = me.Handle; AddChildViewController(TableViewController); ContainerView.AddSubview(TableViewController.View); View.AddConstraint(NSLayoutConstraint.Create(TableViewController.View, NSLayoutAttribute.Top, NSLayoutRelation.Equal, ContainerView, NSLayoutAttribute.Top, 1, 0)); View.AddConstraint(NSLayoutConstraint.Create(TableViewController.View, NSLayoutAttribute.Right, NSLayoutRelation.Equal, ContainerView, NSLayoutAttribute.Right, 1, 0)); View.AddConstraint(NSLayoutConstraint.Create(TableViewController.View, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, ContainerView, NSLayoutAttribute.Bottom, 1, 0)); View.AddConstraint(NSLayoutConstraint.Create(TableViewController.View, NSLayoutAttribute.Left, NSLayoutRelation.Equal, ContainerView, NSLayoutAttribute.Left, 1, 0)); FooterLabel.Text = DrawerShared.GetFooterText(); }
public void SetFont(Font f) { if (f != _lastFont) { _lastFont = f; // We have a Xamarin.Forms.Font object. We need a CTFont. X.F.Font has // ToUIFont() but not a Core Text version of same. So we make a UIFont first. //_font_ui = _lastFont.ToUIFont (); // TODO temporary hack _font_ui = UIFont.SystemFontOfSize(_lastFont.Size); _font_ct = new CTFont(_font_ui.Name, _font_ui.PointSize); // With Core Text, it is important that we use a CTStringAttributes() with the // NSAttributedString constructor. // TODO maybe we should have the text color be separate, have it be an arg on SetFont? _ct_attr = new CTStringAttributes { Font = _font_ct, ForegroundColorFromContext = true, //ForegroundColor = _clr_cg, // ParagraphStyle = new CTParagraphStyle(new CTParagraphStyleSettings() { Alignment = CTTextAlignment.Center }) }; } }
public void BackgroundColor() { var sa = new CTStringAttributes(); Assert.DoesNotThrow(() => { sa.BackgroundColor = TestRuntime.GetCGColor(UIColor.Blue); }, "#0"); Assert.DoesNotThrow(() => { var x = sa.BackgroundColor; }, "#1"); }
protected override void Dispose (bool disposing) { Font = null; attributes = null; caretView = null; base.Dispose (disposing); }
private void prepareTextFields() { var placeholderAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = UIColor.White.ColorWithAlpha(0.5f) }.Dictionary ); EmailTextField.ReturnKeyType = UIReturnKeyType.Next; EmailTextField.TintColor = UIColor.White; EmailTextField.AttributedPlaceholder = new NSAttributedString(Resources.LoginSignUpEmailPlaceholder, placeholderAttributes); PasswordTextField.ReturnKeyType = UIReturnKeyType.Next; PasswordTextField.TintColor = UIColor.White; PasswordTextField.AttributedPlaceholder = new NSAttributedString(Resources.LoginSignUpPasswordPlaceholder, placeholderAttributes); ForgotPasswordButton.SetTitle(Resources.LoginForgotPassword, UIControlState.Normal); var underscoreAttributes = new CTStringAttributes(new UIStringAttributes { UnderlineColor = UIColor.White, ForegroundColor = UIColor.White, UnderlineStyle = NSUnderlineStyle.Single, Font = UIFont.SystemFontOfSize(12, UIFontWeight.Medium) }.Dictionary); PrivacyPolicyButton.SetAttributedTitle( new NSAttributedString(Resources.PrivacyPolicy, underscoreAttributes), UIControlState.Normal); TermsOfServiceButton.SetAttributedTitle( new NSAttributedString(Resources.TermsOfService, underscoreAttributes), UIControlState.Normal); }
public void HorizontalInVerticalForms() { var sa = new CTStringAttributes(); Assert.DoesNotThrow(() => { sa.HorizontalInVerticalForms = 1; }, "#0"); Assert.DoesNotThrow(() => { var x = sa.HorizontalInVerticalForms; }, "#1"); }
public void EnumerateCaretOffsets() { if (!TestRuntime.CheckXcodeVersion(7, 0)) { Assert.Ignore("Requires iOS9+ or macOS 10.11+"); } var sa = new CTStringAttributes(); sa.ForegroundColor = UIColor.Blue.CGColor; sa.Font = new CTFont("Georgia-BoldItalic", 24); sa.UnderlineStyle = CTUnderlineStyle.Double; // It does not seem to do anything sa.UnderlineColor = UIColor.Blue.CGColor; sa.UnderlineStyleModifiers = CTUnderlineStyleModifiers.PatternDashDotDot; var attributedString = new NSAttributedString("Hello world.\nWoohooo!\nThere", sa); var line = new CTLine(attributedString); bool executed = false; #if XAMCORE_2_0 line.EnumerateCaretOffsets((double o, nint charIndex, bool leadingEdge, ref bool stop) => { #else line.EnumerateCaretOffsets((double o, int charIndex, bool leadingEdge, ref bool stop) => { #endif executed = true; }); Assert.IsTrue(executed); }
protected override void Dispose(bool disposing) { Font = null; attributes = null; caretView = null; base.Dispose(disposing); }
public static NSMutableAttributedString ToNsAttributedString(this AttributedGlyphRun <TFont, TGlyph> glyphRun) { var font = glyphRun.Font; var text = glyphRun.Text.ToString(); var unicodeIndexes = StringInfo.ParseCombiningCharacters(text); var attributes = new CTStringAttributes { ForegroundColorFromContext = true, Font = font.CtFont }; var attributedString = new NSMutableAttributedString(text, attributes); var kernedGlyphs = glyphRun.GlyphInfos; for (int i = 0; i < kernedGlyphs.Count; i++) { var endIndex = (i < unicodeIndexes.Length - 1) ? unicodeIndexes[i + 1] : text.Length; var range = new NSRange(unicodeIndexes[i], endIndex - unicodeIndexes[i]); if (kernedGlyphs[i].KernAfterGlyph is var kern && !(kern is 0)) { attributedString.AddAttribute(CTStringAttributeKey.KerningAdjustment, new NSNumber(kern), range); } if (kernedGlyphs[i].Foreground is Structures.Color foreground) { attributedString.AddAttribute(CTStringAttributeKey.ForegroundColor, ObjCRuntime.Runtime.GetNSObject(foreground.ToCgColor().Handle), range); } } return(attributedString); }
public static NSMutableAttributedString ToNsAttributedString(this AttributedGlyphRun <TFont, TGlyph> glyphRun) { var font = glyphRun.Font; var text = glyphRun.Text; var unicodeIndexes = StringInfo.ParseCombiningCharacters(text); var attributes = new CTStringAttributes { ForegroundColorFromContext = true, Font = font.CtFont }; var attributedString = new NSMutableAttributedString(text, attributes); var kernedGlyphs = glyphRun.KernedGlyphs; for (int i = 0; i < kernedGlyphs.Length; i++) { var kern = kernedGlyphs[i].KernAfterGlyph; if (kern != 0) { var endIndex = (i < unicodeIndexes.Length - 1) ? unicodeIndexes[i + 1] : text.Length; var range = new NSRange(unicodeIndexes[i], endIndex - unicodeIndexes[i]); attributedString.AddAttribute(CTStringAttributeKey.KerningAdjustment, new NSNumber(kern), range); } } return(attributedString); }
public void SimpleValuesSet() { var sa = new CTStringAttributes(); sa.ForegroundColor = UIColor.Blue.CGColor; sa.Font = new CTFont("Georgia-BoldItalic", 24); sa.UnderlineStyle = CTUnderlineStyle.Double; // It does not seem to do anything sa.UnderlineColor = UIColor.Blue.CGColor; sa.UnderlineStyleModifiers = CTUnderlineStyleModifiers.PatternDashDotDot; Assert.IsNull(sa.BaselineClass, "#0"); sa.BaselineClass = CTBaselineClass.IdeographicHigh; Assert.AreEqual(CTBaselineClass.IdeographicHigh, sa.BaselineClass, "#1"); sa.SetBaselineInfo(CTBaselineClass.Roman, 13); sa.SetBaselineInfo(CTBaselineClass.IdeographicHigh, 3); sa.SetWritingDirection(CTWritingDirection.LeftToRight); var size = new SizeF(300, 300); UIGraphics.BeginImageContext(size); var gctx = UIGraphics.GetCurrentContext(); gctx.SetFillColor(UIColor.Green.CGColor); var attributedString = new NSAttributedString("Test_ME~`", sa); using (var textLine = new CTLine(attributedString)) { textLine.Draw(gctx); } UIGraphics.EndImageContext(); }
void SelectFont() { var f = _lastFont; var name = "Helvetica"; if (f.FontFamily == "Monospace") { if (f.IsBold) { name = "Courier-Bold"; } else { name = "Courier"; } } else if (f.FontFamily == "DBLCDTempBlack") { #if MONOMAC name = "Courier-Bold"; #else name = f.FontFamily; #endif } else if (f.IsBold) { name = "Helvetica-Bold"; } _attrs = new CTStringAttributes { Font = new CTFont(name, f.Size), ForegroundColorFromContext = true, }; }
public static XIR.Image RemoteRepresentation(this CTFont ctfont) { var atts = new CTStringAttributes(); atts.Font = ctfont; var attdString = new NSAttributedString(exampleString, atts.Dictionary); return(attdString.RemoteRepresentation()); }
public static XIR.Image RemoteRepresentation(this NSFont nsfont) { var atts = new CTStringAttributes(); atts.Font = new CTFont(nsfont.FontName, nsfont.PointSize); var attdString = new NSAttributedString(exampleString, atts.Dictionary); return(RemoteRepresentation(attdString)); }
private NSAttributedString IterateChildNodes(XElement element, CTStringAttributes baseAttribs) { NSMutableAttributedString mutString = new NSMutableAttributedString (""); foreach (var child in element.Nodes()) { NSAttributedString formatted = NodeToAttributedString (child, baseAttribs); if (formatted != null) mutString.Append (formatted); } return mutString; }
public SimpleCoreTextView(RectangleF frame) : base(frame) { Layer.GeometryFlipped = true; // For ease of interaction with the CoreText coordinate system. attributes = new CTStringAttributes (); Text = string.Empty; Font = UIFont.SystemFontOfSize (18); BackgroundColor = UIColor.Clear; caretView = new SimpleCaretView (RectangleF.Empty); }
public SimpleCoreTextView(CGRect frame) : base(frame) { Layer.GeometryFlipped = true; // For ease of interaction with the CoreText coordinate system. attributes = new CTStringAttributes(); Text = string.Empty; Font = UIFont.SystemFontOfSize(18); BackgroundColor = UIColor.Clear; caretView = new SimpleCaretView(CGRect.Empty); }
public NSAttributedString ToAttributedString(UIFont baseFont) { if (_asAttributedString == null) { CTStringAttributes attrs = new CTStringAttributes (); attrs.Font = new CTFont(baseFont.Name, baseFont.PointSize); attrs.ForegroundColor = UIColor.Black.CGColor; _asAttributedString = IterateChildNodes (Definition, attrs); } return _asAttributedString; }
private void prepareTextFields() { var placeholderAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = UIColor.White.ColorWithAlpha(0.5f) }.Dictionary ); PasswordTextField.TintColor = UIColor.White; PasswordTextField.AttributedPlaceholder = new NSAttributedString(Resources.LoginSignUpPasswordPlaceholder, placeholderAttributes); }
public static FontHolder Create(string faceName, int size, int weight, font_style italic, font_decoration decoration, ref font_metrics fm) { var possibleFonts = faceName.Split(',').ToList(); possibleFonts.Add("Helvetica"); // Make sure there's a font in the list. CTFont font = null; foreach (var fontName in possibleFonts) { // faceName = faceName; // normalize between WPF and Mac for ways to reference custom fonts. font = new CTFont(fontName.TrimEnd().Replace("./#", ""), size); // Bold & italic are properties of the CTFont var traits = CTFontSymbolicTraits.None; if (italic == font_style.fontStyleItalic) { traits |= CTFontSymbolicTraits.Italic; } if (weight > 400) { traits |= CTFontSymbolicTraits.Bold; } font = font.WithSymbolicTraits(font.Size, traits, traits); if (font != null) { break; } } var strAttrs = new CTStringAttributes { Font = font }; // initial size must be unscaled when getting these metrics fm.ascent = (int)Math.Round(font.AscentMetric); fm.descent = (int)Math.Round(font.DescentMetric); fm.height = (int)Math.Round(font.AscentMetric + font.DescentMetric); fm.x_height = (int)Math.Round(font.XHeightMetric); fm.draw_spaces = decoration.HasFlag(font_decoration.font_decoration_underline) || decoration.HasFlag(font_decoration.font_decoration_linethrough); var fontHolder = new FontHolder { FaceName = faceName, Size = size, Attributes = strAttrs, Decoration = decoration, Weight = weight }; return(fontHolder); }
public void Runs() { using (var mas = new NSMutableAttributedString("Bonjour")) using (var rd = new CTRunDelegate(new MyOps())) { var sa = new CTStringAttributes() { RunDelegate = rd, }; mas.SetAttributes(sa, new NSRange(3, 3)); using (var fs = new CTFramesetter(mas)) { Assert.True(MyOps.Ascent, "Ascent called"); Assert.True(MyOps.Descent, "Descent called"); Assert.True(MyOps.Width, "Width called"); } } }
private void prepareTextFields() { TimeLabel.Font = TimeLabel.Font.GetMonospacedDigitFont(); var stringAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = Color.StartTimeEntry.Placeholder.ToNativeColor() }.Dictionary ); DescriptionTextField.TintColor = Color.StartTimeEntry.Cursor.ToNativeColor(); DescriptionTextField.AttributedPlaceholder = new NSAttributedString(Resources.StartTimeEntryPlaceholder, stringAttributes); DescriptionTextField.BecomeFirstResponder(); }
public void CIAttributedTextImageGenerator() { TestRuntime.AssertXcodeVersion(9, 0); using (var f = new CIAttributedTextImageGenerator()) { Assert.Null(f.Text, "NSAttributedString/default"); var attr = new CTStringAttributes() { ForegroundColorFromContext = true, Font = new CTFont("Arial", 24) }; using (var s = new NSAttributedString("testString", attr)) { f.Text = s; Assert.NotNull(f.Text, "NSAttributedString/not-null"); } } }
private void prepareTextFields() { var stringAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = UIColor.White.ColorWithAlpha(0.5f) }.Dictionary ); EmailTextField.TintColor = UIColor.White; EmailTextField.AttributedPlaceholder = new NSAttributedString(Resources.LoginSignUpEmailPlaceholder, stringAttributes); PasswordTextField.TintColor = UIColor.White; PasswordTextField.AttributedPlaceholder = new NSAttributedString(Resources.LoginSignUpPasswordPlaceholder, stringAttributes); ForgotPasswordButton.SetTitle(Resources.LoginForgotPassword, UIControlState.Normal); }
private static CTStringAttributes GetDefaultAttributes( string contextFontName = null, float contextFontSize = 12f, string contextFontColor = null) { var ctattributes = new CTStringAttributes(); var font = contextFontName == null ? new CTFont(CTFontUIFontType.System, contextFontSize, NSLocale.CurrentLocale.Identifier) : new CTFont(contextFontName, contextFontSize); ctattributes.Font = font; if (contextFontColor != null) { ctattributes.ForegroundColor = contextFontColor.Parse().ToCGColor(); } return(ctattributes); }
private void SetText() { CTStringAttributes attrs = new CTStringAttributes(); string text = Element.GetText(out List <HyperlinkLabelLink> links); if (text != null) { var str = new NSMutableAttributedString(text); str.AddAttribute(UIStringAttributeKey.Font, Element.Font.ToUIFont(), new NSRange(0, str.Length)); var textColor = (Color)Element.GetValue(Label.TextColorProperty); str.AddAttribute(UIStringAttributeKey.ForegroundColor, textColor.ToUIColor(Color.Black), new NSRange(0, str.Length)); foreach (var item in links) { str.AddAttribute(UIStringAttributeKey.Link, new NSUrl(item.Link), new NSRange(item.Start, item.Text.Length)); } Control.AttributedText = str; } }
UITextField AddTextFieldWithName(string name, string text, UIView overlayView, IEnumerable <UIView> previousRowItems, List <NSLayoutConstraint> constraints) { UILabel titleLabel = StyleUtilities.CreateStandardLabel(); titleLabel.Text = name; overlayView.AddSubview(titleLabel); var attributes = new CTStringAttributes(); attributes.ForegroundColor = StyleUtilities.DetailOnOverlayPlaceholderColor.CGColor; UITextField valueField = new UITextField { WeakDelegate = this, Font = StyleUtilities.StandardFont, TextColor = StyleUtilities.DetailOnOverlayColor, Text = text, AttributedPlaceholder = new NSAttributedString("Type here...".LocalizedString("Placeholder for profile text fields"), attributes), TranslatesAutoresizingMaskIntoConstraints = false }; overlayView.AddSubview(valueField); // Ensure sufficient spacing from the row above this one foreach (UIView previousRowItem in previousRowItems) { constraints.Add(NSLayoutConstraint.Create(titleLabel, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, previousRowItem, NSLayoutAttribute.Bottom, 1f, MinimumVerticalSpacingBetweenRows)); } // Place the title directly above the value constraints.Add(NSLayoutConstraint.Create(valueField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, titleLabel, NSLayoutAttribute.Bottom, 1f, 0f)); // Position the title and value within the overlay view constraints.Add(NSLayoutConstraint.Create(titleLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Leading, 1f, StyleUtilities.ContentHorizontalMargin)); constraints.Add(NSLayoutConstraint.Create(valueField, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, titleLabel, NSLayoutAttribute.Leading, 1f, 0f)); constraints.Add(NSLayoutConstraint.Create(valueField, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Trailing, 1f, -1 * StyleUtilities.ContentHorizontalMargin)); return(valueField); }
private void prepareViews() { //This is needed for the ImageView.TintColor bindings to work foreach (var button in getButtons()) { button.SetImage( button.ImageForState(UIControlState.Normal) .ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal ); } TimeLabel.Font = TimeLabel.Font.GetMonospacedDigitFont(); var stringAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = Color.StartTimeEntry.Placeholder.ToNativeColor() }.Dictionary ); DescriptionTextView.TintColor = Color.StartTimeEntry.Cursor.ToNativeColor(); DescriptionTextView.BecomeFirstResponder(); }
private void prepareViews() { //This is needed for the ImageView.TintColor bindings to work BillableButton.SetImage( BillableButton.ImageForState(UIControlState.Normal) .ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), UIControlState.Normal ); TimeLabel.Font = TimeLabel.Font.GetMonospacedDigitFont(); var stringAttributes = new CTStringAttributes( new UIStringAttributes { ForegroundColor = Color.StartTimeEntry.Placeholder.ToNativeColor() }.Dictionary ); DescriptionTextField.TintColor = Color.StartTimeEntry.Cursor.ToNativeColor(); DescriptionTextField.AttributedPlaceholder = new NSAttributedString(Resources.StartTimeEntryPlaceholder, stringAttributes); DescriptionTextField.BecomeFirstResponder(); }
public override void DrawRect(CGRect dirtyRect) { base.DrawRect(dirtyRect); // Use Core Graphic routines to draw our UI using (CGContext context = NSGraphicsContext.CurrentContext.GraphicsPort) { // Fill the screening color. CGPath path = new CGPath(); CGRect frame = new CGRect(0, 0, base.Frame.Width, base.Frame.Height); path.AddRect(frame); ColorView.SetScreeningColor(_screening, context); context.AddPath(path); context.DrawPath(CGPathDrawingMode.Fill); // Draw screening information. context.TranslateCTM(2, ScreeningsView.VerticalTextOffset); context.SetTextDrawingMode(CGTextDrawingMode.Fill); ColorView.SetScreeningColor(_screening, context, true); CTStringAttributes attrs = new CTStringAttributes(); attrs.ForegroundColorFromContext = true; attrs.Font = ScreeningControl.StandardFont; var textPosition = new CGPoint(0, _lineHeight); string[] lines = _screening.ToScreeningLabelString().Split('\n'); foreach (var line in lines) { context.TextPosition = textPosition; var attributedString = new NSAttributedString(line, attrs); using (var textLine = new CTLine(attributedString)) { textLine.Draw(context); } textPosition.Y -= _lineHeight; } } NeedsDisplay = true; }
public static NSAttributedString ToAttributedStringWithMnemonic(this string value, NSDictionary attributes = null) { if (value == null) { return(null); } var match = Regex.Match(value, @"(?<=([^&](?:[&]{2})*)|^)[&](?![&])"); if (match.Success) { value = value.Remove(match.Index, 1); value = value.Replace("&&", "&"); var str = attributes != null ? new NSMutableAttributedString(value, attributes) : new NSMutableAttributedString(value); var attr = new CTStringAttributes(); attr.UnderlineStyle = CTUnderlineStyle.Single; str.AddAttributes(attr, new NSRange(match.Index, 1)); return(str); } else { value = value.Replace("&&", "&"); return(attributes != null ? new NSAttributedString(value, attributes) : new NSAttributedString(value)); } }
private static NSMutableAttributedString buildAttributedString(string text, Font font, Color?fontColor = null) { // Create a new attributed string definition var ctAttributes = new CTStringAttributes(); // Font attribute ctAttributes.Font = font.nativeFont; // -- end font if (fontColor.HasValue) { // Font color var fc = fontColor.Value; var cgColor = new CGColor(fc.R / 255f, fc.G / 255f, fc.B / 255f, fc.A / 255f); ctAttributes.ForegroundColor = cgColor; ctAttributes.ForegroundColorFromContext = false; // -- end font Color } if (font.Underline) { // Underline #if MONOMAC int single = (int)AppKit.NSUnderlineStyle.Single; int solid = (int)AppKit.NSUnderlinePattern.Solid; var attss = single | solid; ctAttributes.UnderlineStyleValue = attss; #else ctAttributes.UnderlineStyleValue = 1; #endif // --- end underline } if (font.Strikeout) { // StrikeThrough // NSColor bcolor = NSColor.Blue; // NSObject bcolorObject = new NSObject(bcolor.Handle); // attsDic.Add(NSAttributedString.StrikethroughColorAttributeName, bcolorObject); // #if MACOS // int stsingle = (int)MonoMac.AppKit.NSUnderlineStyle.Single; // int stsolid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid; // var stattss = stsingle | stsolid; // var stunderlineObject = NSNumber.FromInt32(stattss); // #else // var stunderlineObject = NSNumber.FromInt32 (1); // #endif // // attsDic.Add(StrikethroughStyleAttributeName, stunderlineObject); // --- end underline } // Text alignment var alignment = CTTextAlignment.Left; var alignmentSettings = new CTParagraphStyleSettings(); alignmentSettings.Alignment = alignment; var paragraphStyle = new CTParagraphStyle(alignmentSettings); ctAttributes.ParagraphStyle = paragraphStyle; // end text alignment NSMutableAttributedString atts = new NSMutableAttributedString(text, ctAttributes.Dictionary); return(atts); }
void drawLabel(CGContext ctx, CGRect rect, nfloat yCoord, nfloat xCoord, CTTextAlignment alignment, UIColor color, string label, bool flipContext = true) { Console.WriteLine("Finish Draw code"); var attrString = new NSMutableAttributedString (label); var range = new NSRange (0, attrString.Length); var uiFont = UIFont.FromName("HelveticaNeue-Medium", range.Length > 1 ? 15 : 22); var font = new CTFont (uiFont.Name, uiFont.PointSize); //((uiFont.Name as NSString) as CFString, uiFont.pointSize, nil); var path = new CGPath (); var alignStyle = new CTParagraphStyle (new CTParagraphStyleSettings { Alignment = alignment }); var attributes = new CTStringAttributes { Font = font, ForegroundColor = color.CGColor, ParagraphStyle = alignStyle }; attrString.SetAttributes(attributes, new NSRange (0, attrString.Length)); var target = new CGSize (nfloat.MaxValue, nfloat.MaxValue); var fit = new NSRange (0, 0); var framesetter = new CTFramesetter (attrString); var frameSize = framesetter.SuggestFrameSize(range, null, target, out fit); var textRect = new CGRect (xCoord - (frameSize.Width / 2), yCoord - (frameSize.Height / 2), frameSize.Width, frameSize.Height); path.AddRect(textRect); var frame = framesetter.GetFrame(range, path, null); if (flipContext) { ctx.SaveState(); ctx.TranslateCTM(0, rect.Height); ctx.ScaleCTM(1, -1); frame.Draw(ctx); ctx.RestoreState(); } else { frame.Draw(ctx); } }
public CoreGraphicsFontMetrics(CTStringAttributes attrs) { this.attrs = attrs; }
private static void DrawText(this CGContext context, string source, float x, float y, string fontName, float fontSize, bool isCenter) { var stringAttributes = new CTStringAttributes { ForegroundColorFromContext = true, Font = new CTFont(fontName, fontSize) }; var attributedString = new NSAttributedString(source, stringAttributes); context.TextPosition = new PointF(x, y); using (var textLine = new CTLine(attributedString)) { if (isCenter) context.TextPosition = new PointF((float)(x - (textLine.GetTypographicBounds() / 2)), y); textLine.Draw(context); } }
private static NSMutableAttributedString buildAttributedString(string text, Font font, Color? fontColor=null) { // Create a new attributed string definition var ctAttributes = new CTStringAttributes (); // Font attribute ctAttributes.Font = font.nativeFont; // -- end font if (fontColor.HasValue) { // Font color var fc = fontColor.Value; var cgColor = new CGColor(fc.R / 255f, fc.G / 255f, fc.B / 255f, fc.A / 255f); ctAttributes.ForegroundColor = cgColor; ctAttributes.ForegroundColorFromContext = false; // -- end font Color } if (font.Underline) { // Underline #if MONOMAC int single = (int)AppKit.NSUnderlineStyle.Single; int solid = (int)AppKit.NSUnderlinePattern.Solid; var attss = single | solid; ctAttributes.UnderlineStyleValue = attss; #else ctAttributes.UnderlineStyleValue = 1; #endif // --- end underline } if (font.Strikeout) { // StrikeThrough // NSColor bcolor = NSColor.Blue; // NSObject bcolorObject = new NSObject(bcolor.Handle); // attsDic.Add(NSAttributedString.StrikethroughColorAttributeName, bcolorObject); // #if MACOS // int stsingle = (int)MonoMac.AppKit.NSUnderlineStyle.Single; // int stsolid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid; // var stattss = stsingle | stsolid; // var stunderlineObject = NSNumber.FromInt32(stattss); // #else // var stunderlineObject = NSNumber.FromInt32 (1); // #endif // // attsDic.Add(StrikethroughStyleAttributeName, stunderlineObject); // --- end underline } // Text alignment var alignment = CTTextAlignment.Left; var alignmentSettings = new CTParagraphStyleSettings(); alignmentSettings.Alignment = alignment; var paragraphStyle = new CTParagraphStyle(alignmentSettings); ctAttributes.ParagraphStyle = paragraphStyle; // end text alignment NSMutableAttributedString atts = new NSMutableAttributedString(text,ctAttributes.Dictionary); return atts; }
void SelectFont () { var f = _lastFont; var name = "Helvetica"; if (f.FontFamily == "Monospace") { if (f.IsBold) { name = "Courier-Bold"; } else { name = "Courier"; } } else if (f.FontFamily == "DBLCDTempBlack") { #if MONOMAC name = "Courier-Bold"; #else name = f.FontFamily; #endif } else if (f.IsBold) { name = "Helvetica-Bold"; } _attrs = new CTStringAttributes { Font = new CTFont (name, f.Size), ForegroundColorFromContext = true, }; }
private NSMutableAttributedString buildAttributedString(string text, Font font, StringFormat format = null, Color? fontColor=null) { // Create a new attributed string definition var ctAttributes = new CTStringAttributes (); // Font attribute ctAttributes.Font = font.nativeFont; // -- end font if (format != null && (format.FormatFlags & StringFormatFlags.DirectionVertical) == StringFormatFlags.DirectionVertical) { //ctAttributes.VerticalForms = true; } if (fontColor.HasValue) { // Font color var fc = fontColor.Value; var cgColor = new CGColor(fc.R / 255f, fc.G / 255f, fc.B / 255f, fc.A / 255f); ctAttributes.ForegroundColor = cgColor; ctAttributes.ForegroundColorFromContext = false; // -- end font Color } if (font.Underline) { // Underline #if MONOMAC int single = (int)AppKit.NSUnderlineStyle.Single; int solid = (int)AppKit.NSUnderlinePattern.Solid; var attss = single | solid; ctAttributes.UnderlineStyleValue = attss; #else ctAttributes.UnderlineStyleValue = 1; #endif // --- end underline } if (font.Strikeout) { // StrikeThrough #if MONOMAC int single = (int)AppKit.NSUnderlineStyle.Single; int solid = (int)AppKit.NSUnderlinePattern.Solid; var attss = single | solid; ctAttributes.UnderlineStyleValue = attss; #else ctAttributes.UnderlineStyleValue = 1; #endif // --- end StrikeThrough } var alignment = CTTextAlignment.Left; var alignmentSettings = new CTParagraphStyleSettings(); alignmentSettings.Alignment = alignment; var paragraphStyle = new CTParagraphStyle(alignmentSettings); ctAttributes.ParagraphStyle = paragraphStyle; // end text alignment NSMutableAttributedString atts = new NSMutableAttributedString(text,ctAttributes.Dictionary); return atts; }
private UITextField AddTextFieldWithName (string name, string text, UIView overlayView, IEnumerable<UIView> previousRowItems, List<NSLayoutConstraint> constraints) { UILabel titleLabel = StyleUtilities.CreateStandardLabel (); titleLabel.Text = name; overlayView.AddSubview (titleLabel); var attributes = new CTStringAttributes (); attributes.ForegroundColor = StyleUtilities.DetailOnOverlayPlaceholderColor.CGColor; UITextField valueField = new UITextField { WeakDelegate = this, Font = StyleUtilities.StandardFont, TextColor = StyleUtilities.DetailOnOverlayColor, Text = text, AttributedPlaceholder = new NSAttributedString("Type here...".LocalizedString("Placeholder for profile text fields"), attributes), TranslatesAutoresizingMaskIntoConstraints = false }; overlayView.AddSubview (valueField); // Ensure sufficient spacing from the row above this one foreach (UIView previousRowItem in previousRowItems) constraints.Add (NSLayoutConstraint.Create (titleLabel, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, previousRowItem, NSLayoutAttribute.Bottom, 1f, MinimumVerticalSpacingBetweenRows)); // Place the title directly above the value constraints.Add (NSLayoutConstraint.Create (valueField, NSLayoutAttribute.Top, NSLayoutRelation.Equal, titleLabel, NSLayoutAttribute.Bottom, 1f, 0f)); // Position the title and value within the overlay view constraints.Add (NSLayoutConstraint.Create (titleLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Leading, 1f, StyleUtilities.ContentHorizontalMargin)); constraints.Add (NSLayoutConstraint.Create (valueField, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, titleLabel, NSLayoutAttribute.Leading, 1f, 0f)); constraints.Add (NSLayoutConstraint.Create (valueField, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Trailing, 1f, -1 * StyleUtilities.ContentHorizontalMargin)); return valueField; }
public CoreGraphicsFontMetrics (CTStringAttributes attrs) { this.attrs = attrs; }
private static NSAttributedString buildAttributedString(string text, Font font, StringFormat format = null, Color?fontColor = null) { var ctAttributes = new CTStringAttributes(); ctAttributes.Font = font.nativeFont; if (fontColor.HasValue) { ctAttributes.ForegroundColor = fontColor.Value.ToCGColor(); ctAttributes.ForegroundColorFromContext = false; } if (font.Underline) { ctAttributes.UnderlineStyle = CTUnderlineStyle.Single; } // font.Strikeout - Not used by CoreText, we have to process it ourselves if (text.IndexOf('\0') >= 0) { text = text.Replace("\0", ""); } if (format == null || format.HotkeyPrefix == System.Drawing.Text.HotkeyPrefix.None) { return(new NSAttributedString(text, ctAttributes.Dictionary)); } var sb = new StringBuilder(); bool wasHotkey = false; int end = text.Length - 1; for (int i = 0; i < text.Length; ++i) { char c = text[i]; if (wasHotkey || c != '&' || i == end) { sb.Append(c); wasHotkey = false; } else if (c == '&') { wasHotkey = true; } } var atts = new NSMutableAttributedString(sb.ToString(), ctAttributes.Dictionary); // Underline wasHotkey = false; if (format.HotkeyPrefix == System.Drawing.Text.HotkeyPrefix.Show) { int index = 0; for (int i = 0; i < text.Length; ++i) { char c = text[i]; if (wasHotkey) { atts.AddAttributes( new CTStringAttributes() { UnderlineStyle = CTUnderlineStyle.Single }, new NSRange(index, 1)); index++; wasHotkey = false; } else if (c == '&' && i != end && text[i + 1] != '&') { wasHotkey = true; } else { index++; } } } return(atts); }
private NSAttributedString NodeToAttributedString(XNode node, CTStringAttributes baseAttribs) { CTStringAttributes newAttribs; switch (node.NodeType) { case XmlNodeType.Text: string text = ((XText)node).Value; text = r_findExcessWhitespace.Replace (text, " "); return new NSAttributedString (text, baseAttribs); case XmlNodeType.Element: switch (((XElement)node).Name.LocalName) { case "b": newAttribs = new CTStringAttributes (); newAttribs.Font = Bolded (baseAttribs.Font); return IterateChildNodes ((XElement)node, newAttribs); case "i": newAttribs = new CTStringAttributes (); newAttribs.Font = Italicized (baseAttribs.Font); return IterateChildNodes ((XElement)node, newAttribs); case "br": return new NSAttributedString("\n", baseAttribs); default: break; } break; } return null; }