public override void DrawRect(CGRect dirtyRect) { NSColorList colors = NSColorList.ColorListNamed("System"); CGRect rect = Bounds; rect.Height = 12; var style = (NSMutableParagraphStyle)NSParagraphStyle.DefaultParagraphStyle.MutableCopy(); style.Alignment = NSTextAlignment.Right; var attrs = new NSStringAttributes { Font = NSFont.SystemFontOfSize(8), ForegroundColor = NSColor.LabelColor, ParagraphStyle = style }; foreach (NSString key in colors.AllKeys()) { if (DrawColors) { NSColor color = colors.ColorWithKey(key); color.Set(); NSGraphics.RectFill(rect); } if (DrawTitles) { key.DrawString(rect, attrs.Dictionary); } rect.Y += 12; } }
public void AddItem(string identifier, string title) { var layer = new CATextLayer(); layer.String = title; layer.SetFont("SF UI Text Bold"); layer.FontSize = 12; layer.ForegroundColor = NSColor.FromRgb(80, 80, 80).CGColor; layer.ContentsScale = NSScreen.MainScreen.BackingScaleFactor; var attrs = new NSStringAttributes(); attrs.Font = NSFont.FromFontName("SF UI Text Bold", 12); var stringSize = NSStringDrawing.StringSize(layer.String, attrs); var frame = new CGRect(new CGPoint(0, 0), stringSize); layer.Frame = frame; layer.AnchorPoint = new CGPoint(0, 0.5f); items.Add(new BreadcrumbViewItem { Identifier = identifier, Title = title, Layer = layer }); Layer.AddSublayer(layer); NeedsDisplay = true; }
private static void RenderSolutionNameIcon(string name) { if (!string.IsNullOrWhiteSpace(name)) { const float margin = 4; NSString text = (NSString)name; var paragraphStyle = (NSParagraphStyle)NSParagraphStyle.DefaultParagraphStyle.MutableCopy(); paragraphStyle.Alignment = NSTextAlignment.Center; var attributes = new NSStringAttributes() { Font = NSFont.SystemFontOfSize(19, NSFontWeight.Regular), ForegroundColor = NSColor.White, ParagraphStyle = paragraphStyle }; var textRect = new CGSize(_defaultImage.Size.Width - margin * 2, _defaultImage.Size.Height - 2 * margin); var rect = text.BoundingRectWithSize(textRect, NSStringDrawingOptions.UsesLineFragmentOrigin, attributes.Dictionary); var centerAdjustment = _defaultImage.Size.Width - rect.Width - 2 * margin; rect.Offset(margin + centerAdjustment / 2, margin); var brandedImage = NSImage.ImageWithSize(_defaultImage.Size, false, (dstRect) => { _defaultImage.Draw(dstRect); DrawBackgroundInRect(rect); text.DrawInRect(rect, attributes); return(true); }); NSApplication.SharedApplication.ApplicationIconImage = brandedImage; } else { NSApplication.SharedApplication.ApplicationIconImage = _defaultImage; } }
public override void DrawRect (CGRect dirtyRect) { NSColorList colors = NSColorList.ColorListNamed ("System"); CGRect rect = Bounds; rect.Height = 12; var style = (NSMutableParagraphStyle)NSParagraphStyle.DefaultParagraphStyle.MutableCopy (); style.Alignment = NSTextAlignment.Right; var attrs = new NSStringAttributes { Font = NSFont.SystemFontOfSize (8), ForegroundColor = NSColor.LabelColor, ParagraphStyle = style }; foreach (NSString key in colors.AllKeys ()) { if (DrawColors) { NSColor color = colors.ColorWithKey (key); color.Set (); NSGraphics.RectFill (rect); } if (DrawTitles) key.DrawString (rect, attrs.Dictionary); rect.Y += 12; } }
public static NSAttributedString AttributedTitle(string title, NSColor color, String fontName, float fontSize, NSTextAlignment textAlignment) { NSMutableParagraphStyle ps = new NSMutableParagraphStyle(); ps.Alignment = textAlignment; ps.LineSpacing = 0.0f; NSColor fontColor = color; NSFont font = NSFont.FromFontName(fontName, fontSize); if (font == null) { font = NSFont.SystemFontOfSize(fontSize); } NSString titleObj = new NSString(title); NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = font; attributes.ForegroundColor = fontColor; attributes.ParagraphStyle = ps; attributes.ToolTip = titleObj; NSAttributedString buttonString = new NSAttributedString(title, attributes); return(buttonString); }
private void ProcessTextFormat(NSStringAttributes attributes) { var str = new NSString("A"); var bounds = str.BoundingRectWithSize( new CGSize(1000, 1000), 0, attributes.Dictionary); if ((nfloat)CharacterWidth != bounds.Width || (nfloat)CharacterHeight != bounds.Height) { CharacterWidth = bounds.Right; CharacterHeight = //bounds.Bottom attributes.Font.Ascender - attributes.Font.Descender; } int columns = Convert.ToInt32(Math.Floor(Frame.Width / CharacterWidth)); int rows = Convert.ToInt32(Math.Floor(Frame.Height / CharacterHeight)); if (Columns != columns || Rows != rows) { Columns = columns; Rows = rows; ResizeTerminal(); if (VtConnection != null) { VtConnection.SetTerminalWindowSize(columns, rows, 800, 600); } } }
private static NSAttributedString GenerateAttributeString(string id, string title, Uri link, string linkTooltip) { if (string.IsNullOrEmpty(title)) { return(null); } var attributedBuffer = new NSMutableAttributedString(); attributedBuffer.BeginEditing(); var normalText = new NSStringAttributes { ForegroundColor = NSColor.ControlText }; if (!string.IsNullOrEmpty(id)) { var linkAttributes = new NSStringAttributes { LinkUrl = link, ToolTip = linkTooltip }; attributedBuffer.Append(new NSAttributedString(id, linkAttributes)); attributedBuffer.Append(new NSAttributedString(": ", normalText)); } attributedBuffer.Append(new NSAttributedString(title, normalText)); attributedBuffer.EndEditing(); return(attributedBuffer); }
public static CGSize DrawString(this NSString item, CGRect rect, UIFont font, UILineBreakMode mode, UITextAlignment alignment) { // Get paragraph style var labelStyle = new NSMutableParagraphStyle(NSParagraphStyle.DefaultParagraphStyle.MutableCopy() as AppKit.NSMutableParagraphStyle); // Adjust alignment labelStyle.Alignment = alignment; // Adjust line break mode labelStyle.LineBreakMode = mode; // Define attributes var attributes = new NSStringAttributes() { Font = font.NSFont, ForegroundColor = UIStringDrawing.FillColor, ParagraphStyle = labelStyle }; // Preform drawing item.DrawInRect(rect, attributes); // Return new bounding size return(new CGSize(rect.Width, rect.Height)); }
public static NSAttributedString AttributedPartialTitle(string title, List <string> keyWordsList, NSColor fontColor, string fontName, float fontSize, NSTextAlignment textAlignment, NSLineBreakMode breakMode) { string patten = "\\b("; int i = 0; foreach (var item in keyWordsList) { if (i != 0) { patten = patten + "|" + item; } else { patten = patten + item; } i++; } patten = patten + ")\\b"; string [] results = Regex.Split(title, patten); NSMutableParagraphStyle ps = new NSMutableParagraphStyle(); ps.Alignment = textAlignment; ps.LineBreakMode = breakMode; NSMutableAttributedString attrTitle = new NSMutableAttributedString(); foreach (var item in results) { //Console.WriteLine ("result:{0}", item); if (item.Length == 0) { continue; } if (keyWordsList.Contains(item)) { NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = NSFont.FromFontName(fontName + " Bold Italic", fontSize); attributes.ForegroundColor = Utility.ColorWithRGB(0, 0, 0, 0.45f); attributes.ParagraphStyle = ps; NSAttributedString attrString = new NSAttributedString(item, attributes); attrTitle.Append(attrString); } else { NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = NSFont.FromFontName(fontName, fontSize); attributes.ForegroundColor = fontColor; attributes.ParagraphStyle = ps; NSAttributedString attrString = new NSAttributedString(item, attributes); attrTitle.Append(attrString); } } return(attrTitle); }
// Shared initialization code void Initialize() { repeatCount = 1; textAttrs = new NSStringAttributes() { Font = NSFont.UserFixedPitchFontOfSize(16) }; }
/// <summary> /// Outputs the log. /// </summary> /// <param name="text">Text.</param> /// <param name="attributes">Attributes.</param> private void OutputLog(string text, NSStringAttributes attributes = null) { var textToAdd = attributes == null ? new NSAttributedString(text) : new NSAttributedString(text, attributes); var stor = LogField.TextStorage; stor.BeginEditing(); stor.Append(textToAdd); stor.EndEditing(); }
public override void Draw(PdfDisplayBox box) { //base.Draw (box); CGRect sourceRect = new CGRect(0, 0, 0, 0); CGRect topHalf; CGRect destRect; // Drag image. // ........... // Source rectangle. sourceRect.Size = PdfImage.Size; // Represent the top half of the page. topHalf = GetBoundsForBox(box); Utility.ColorWithHexColorValue("#ffffff", 1.0f).Set(); NSGraphics.RectFill(topHalf); // Scale and center image within top half of page. destRect = sourceRect; destRect.Height -= 120; destRect.Y += 60; // Draw. //Console.WriteLine("left:{0},top:{1},width:{2},height:{3}",destRect.X,destRect.Y,destRect.Width,destRect.Height); PdfImage.DrawInRect(destRect, new CGRect(0, 0, 0, 0), NSCompositingOperation.SourceOver, 1.0f); // Draw name. // ........... destRect = GetBoundsForBox(box); destRect.Y = destRect.Height - 44.0f; destRect.Height = 34.0f; destRect.X = 30.0f; destRect.Width -= 60.0f; // Draw label. NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = NSFont.SystemFontOfSize(11); Label.DrawInRect(destRect, attributes); // Draw name. // ........... destRect = GetBoundsForBox(box); destRect.Y = 10.0f; destRect.Height = 17.0f; destRect.X = 30.0f; destRect.Width -= 60.0f; PageFooter.DrawInRect(destRect, attributes); }
public override void UIDrawFooterInRect(WebView sender, CGRect rect) { CGRect destRect = sender.MainFrame.FrameView.Frame; destRect.Height = 44.0f; destRect.X = 30.0f; destRect.Width -= 60.0f; // Draw label. NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = NSFont.SystemFontOfSize(11); "footer".DrawInRect(rect, attributes); }
internal void Draw(CGContext context, float x, float y, UGColor color) { #if __MACOS__ NSStringAttributes attributes = null; using (var nsColor = color.ToNSColor()) { attributes = new NSStringAttributes() { Font = _textFormat.Native, ForegroundColor = nsColor, }; } #else UIStringAttributes attributes = null; using (var uiColor = color.ToUIColor()) { attributes = new UIStringAttributes() { Font = _textFormat.Native, ForegroundColor = uiColor, }; } #endif var bounds = LayoutBounds; var rect = new CGRect( x + bounds.X, y + bounds.Y, bounds.Width, bounds.Height); var scaleMatrix = CGAffineTransformHelper.CreateScale( 1F, -1F, (float)rect.X, (float)rect.Y); try { context.SaveState(); context.ConcatCTM(scaleMatrix); context.TranslateCTM(0, -bounds.Height); #if __MACOS__ _native.DrawInRect(rect, attributes); #else _native.DrawString(rect, attributes); #endif } finally { context.RestoreState(); } }
public override void UIDrawHeaderInRect(WebView sender, CGRect rect) { //throw new System.NotImplementedException (); CGRect destRect = sender.MainFrame.FrameView.Frame; destRect.Y = destRect.Height - 44.0f; destRect.Height = 34.0f; destRect.X = 30.0f; destRect.Width -= 60.0f; // Draw label. NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = NSFont.SystemFontOfSize(11); "header".DrawInRect(rect, attributes); }
public override void ViewDidLoad() { base.ViewDidLoad(); if (View != null && View.Frame.IsEmpty == false) { InitialHeight = View.Frame.Height; } CustomButtonStyles.ApplyStyleMainButton(GuiButtonLogIn, LocalizedStrings.Instance.LocalizedString("Button_LogIn")); CustomButtonStyles.ApplyStyleNavigationButtonV2(GuiButtonStartFreeTrial, LocalizedStrings.Instance.LocalizedString("Button_StartFreeTrial")); GuiTextViewUser.PlaceholderString = LocalizedStrings.Instance.LocalizedString("Placeholder_Username"); GuiTextViewUser.Cell.Title = __LogInViewModel.UserName ?? ""; GuiTextViewUser.LineBreakMode = NSLineBreakMode.TruncatingHead; // ACCOUNT ID DESCRIPTION ... // Initialize Account ID description text with link to a Client Area NSData descriptionData = NSData.FromString("Your account ID can be found in the <a style=\"text-decoration:none\" href=\"https://www.ivpn.net/clientarea/login\">Client Area</a> of the website"); NSDictionary resultDocumentAttributes; NSAttributedString nSAttributed = NSAttributedString.CreateWithHTML(descriptionData, out resultDocumentAttributes); NSStringAttributes descTextAttributes = new NSStringAttributes(); descTextAttributes.Font = GuiTextAccountIdDescription.Font; // keep using preconfigured TextField font descTextAttributes.ForegroundColor = GuiTextAccountIdDescription.TextColor; // keep using preconfigured TextField color descTextAttributes.ParagraphStyle = new NSMutableParagraphStyle { Alignment = NSTextAlignment.Center }; NSMutableAttributedString descriptionString = new NSMutableAttributedString(nSAttributed); descriptionString.AddAttributes(descTextAttributes, new NSRange(0, nSAttributed.Length)); GuiTextAccountIdDescription.AllowsEditingTextAttributes = true; // it is important GuiTextAccountIdDescription.Selectable = true; GuiTextAccountIdDescription.AttributedStringValue = descriptionString; // nSAttributed; // ... ACCOUNT ID DESCRIPTION GuiButtonLogIn.Hidden = false; View.OnApperianceChanged += () => { CustomButtonStyles.ApplyStyleNavigationButtonV2(GuiButtonStartFreeTrial, LocalizedStrings.Instance.LocalizedString("Button_StartFreeTrial")); }; }
private void ComputeBounds() { #if __MACOS__ var attributes = new NSStringAttributes() { Font = _textFormat.Native, }; var size = _native.StringSize(attributes); #else var attributes = new UIStringAttributes() { Font = _textFormat.Native, }; var size = _native.GetSizeUsingAttributes(attributes); #endif _LayoutBounds = new UGRect( 0F, 0F, (float)size.Width, (float)size.Height); if (HorizontalAlignment != UGHorizontalAlignment.Left) { if (HorizontalAlignment == UGHorizontalAlignment.Right) { _LayoutBounds.X = Math.Max(0F, _requestedSize.Width - _LayoutBounds.Width); } else if (HorizontalAlignment == UGHorizontalAlignment.Center) { _LayoutBounds.X = Math.Max(0F, (_requestedSize.Width - _LayoutBounds.Width) / 2F); } } if (VerticalAlignment != UGVerticalAlignment.Top) { if (VerticalAlignment == UGVerticalAlignment.Bottom) { _LayoutBounds.Y = Math.Max(0F, _requestedSize.Height - _LayoutBounds.Height); } else if (VerticalAlignment == UGVerticalAlignment.Center) { _LayoutBounds.Y = Math.Max(0F, (_requestedSize.Height - _LayoutBounds.Height) / 2F); } } }
public void DisplayIdle() { topMessage = null; topMessageAction = null; UpdateImage(null); if (Session.Agent.Type == AgentType.Unknown) { textField.StringValue = String.Empty; return; } var paragraphStyle = (NSMutableParagraphStyle)NSParagraphStyle .DefaultParagraphStyle .MutableCopy(); paragraphStyle.LineBreakMode = NSLineBreakMode.TruncatingTail; var attributes = new NSStringAttributes { Font = textField.Font, ForegroundColor = NSColor.HeaderText, ParagraphStyle = paragraphStyle }.Dictionary; var title = new NSMutableAttributedString(Session.Title, attributes); if (Session.SecondaryTitle != null) { title.Append(new NSAttributedString(" │ ", attributes)); title.Append(new NSAttributedString( Session.SecondaryTitle, new NSStringAttributes { Font = textField.Font, ForegroundColor = NSColor.DisabledControlText, ParagraphStyle = paragraphStyle })); } textField.AttributedStringValue = title; }
NSStringAttributes GetAttributes (int attribute) { // ((int)flags << 18) | (fg << 9) | bg; int bg = attribute & 0x1ff; int fg = (attribute >> 9) & 0x1ff; var flags = (FLAGS) (attribute >> 18); if (flags.HasFlag (FLAGS.INVERSE)) { var tmp = bg; bg = fg; fg = tmp; if (fg == Renderer.DefaultColor) fg = Renderer.InvertedDefaultColor; if (bg == Renderer.DefaultColor) bg = Renderer.InvertedDefaultColor; } if (attributes.TryGetValue (attribute, out var result)) return result; NSFont font; if (flags.HasFlag (FLAGS.BOLD)){ if (flags.HasFlag (FLAGS.ITALIC)) font = fontBoldItalic; else font = fontBold; } else if (flags.HasFlag (FLAGS.ITALIC)) font = fontItalic; else font = fontNormal; var nsattr = new NSStringAttributes () { Font = font, ForegroundColor = MapColor (fg, true), BackgroundColor = MapColor (bg, false) }; if (flags.HasFlag (FLAGS.UNDERLINE)) { nsattr.UnderlineColor = nsattr.ForegroundColor; nsattr.UnderlineStyle = (int) NSUnderlineStyle.Single; } attributes [attribute] = nsattr; return nsattr; }
public static NSAttributedString AttributeTitle(string title, NSColor color, float fontsize) { NSMutableParagraphStyle ps = new NSMutableParagraphStyle(); ps.Alignment = NSTextAlignment.Center; NSColor fontColor = color; NSFont font = NSFont.SystemFontOfSize(fontsize); NSString titleObj = new NSString(title); NSStringAttributes attributes = new NSStringAttributes(); attributes.Font = font; attributes.ForegroundColor = fontColor; attributes.ParagraphStyle = ps; attributes.BackgroundColor = NSColor.Clear; attributes.ToolTip = titleObj; NSAttributedString buttonString = new NSAttributedString(title, attributes); return(buttonString); }
public static NSImage CreateIconWithSolutionName(string name, NSImage baseImage) { if (string.IsNullOrWhiteSpace(name)) { return(baseImage); } const float margin = 4; var text = (NSString)name; // setup text styles var paragraphStyle = (NSParagraphStyle)NSParagraphStyle.DefaultParagraphStyle.MutableCopy(); paragraphStyle.Alignment = NSTextAlignment.Center; var attributes = new NSStringAttributes { Font = NSFont.SystemFontOfSize(19, NSFontWeight.Regular), ForegroundColor = NSColor.White, ParagraphStyle = paragraphStyle }; // setup rect var textRect = new CGSize(baseImage.Size.Width - margin * 2, baseImage.Size.Height - 2 * margin); var rect = text.BoundingRectWithSize(textRect, NSStringDrawingOptions.UsesLineFragmentOrigin, attributes.Dictionary); var centerAdjustment = baseImage.Size.Width - rect.Width - 2 * margin; rect.Offset(margin + centerAdjustment / 2, margin); // create image var brandedImage = NSImage.ImageWithSize(baseImage.Size, false, dstRect => { baseImage.Draw(dstRect); DrawBackgroundInRect(rect); text.DrawInRect(rect, attributes); return(true); }); return(brandedImage); }
/// <summary> /// Create attribytes string with a required style /// </summary> public static NSAttributedString Create(string text, NSColor color = null, NSTextAlignment?aligment = null, NSFont font = null) { if (text == null) { text = ""; } NSMutableParagraphStyle paragraphStyle = null; NSStringAttributes stringAttributes = new NSStringAttributes(); if (color != null) { stringAttributes.ForegroundColor = color; } if (font != null) { stringAttributes.Font = font; } if (aligment != null) { if (paragraphStyle == null) { paragraphStyle = new NSMutableParagraphStyle(); } paragraphStyle.Alignment = (NSTextAlignment)aligment; } if (paragraphStyle != null) { stringAttributes.ParagraphStyle = paragraphStyle; } return(new NSAttributedString(text, stringAttributes)); }
public static CGSize DrawString (this NSString item, CGRect rect, UIFont font, UILineBreakMode mode, UITextAlignment alignment) { // Get paragraph style var labelStyle = new NSMutableParagraphStyle(NSParagraphStyle.DefaultParagraphStyle.MutableCopy() as AppKit.NSMutableParagraphStyle); // Adjust alignment labelStyle.Alignment = alignment; // Adjust line break mode labelStyle.LineBreakMode = mode; // Define attributes var attributes = new NSStringAttributes () { Font = font.NSFont, ForegroundColor = UIStringDrawing.FillColor, ParagraphStyle = labelStyle }; // Preform drawing item.DrawInRect(rect, attributes); // Return new bounding size return new CGSize (rect.Width, rect.Height); }
internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition) { if (string.IsNullOrEmpty(text)) { return(new CCTexture2D()); } int imageWidth; int imageHeight; var textDef = textDefinition; var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; textDef.FontSize *= contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; //bool hasPremultipliedAlpha; // font NSFont font = null; var ext = System.IO.Path.GetExtension(textDef.FontName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { try { textDef.FontName = LoadFontFile(textDef.FontName); font = NSFont.FromFontName(textDef.FontName, textDef.FontSize); } catch { CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName); } } else { // font font = NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); } if (font == null) { font = NSFontManager.SharedFontManager.FontWithFamily("Arial", NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); CCLog.Log("{0} not found. Defaulting to Arial.", textDef.FontName); } // color var foregroundColor = NSColor.White; // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? NSTextAlignment.Right : (CCTextAlignment.Center == horizontalAlignment) ? NSTextAlignment.Center : NSTextAlignment.Left; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? NSLineBreakMode.CharWrapping : (CCLabelLineBreak.Word == textDef.LineBreak) ? NSLineBreakMode.ByWordWrapping : NSLineBreakMode.Clipping; var nsparagraphStyle = new NSMutableParagraphStyle(); nsparagraphStyle.SetParagraphStyle(NSMutableParagraphStyle.DefaultParagraphStyle); nsparagraphStyle.LineBreakMode = lineBreak; nsparagraphStyle.Alignment = textAlign; // Create a new attributed string definition var nsAttributes = new NSStringAttributes(); // Font attribute nsAttributes.Font = font; nsAttributes.ForegroundColor = foregroundColor; nsAttributes.ParagraphStyle = nsparagraphStyle; var stringWithAttributes = new NSAttributedString(text, nsAttributes); var realDimensions = stringWithAttributes.Size; // Mac crashes if the width or height is 0 if (realDimensions == SizeF.Empty) { CCLog.Log("Native string:", "Dimensions of native NSAttributedString can not be 0,0"); return(new CCTexture2D()); } var dimensions = new SizeF(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; // // * Note * This seems to only effect Mac because iOS works fine without this work around. // Right Alignment BoundingRectWithSize does not seem to be working correctly when the following conditions are set: // 1) Alignment Right // 2) No dimensions // 3) There are new line characters embedded in the string. // // So we set alignment to Left, calculate our bounds and then restore alignement afterwards before drawing. // if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; // Set our alignment variables to left - see notes above. nsparagraphStyle.Alignment = NSTextAlignment.Left; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } // Calculate our bounding rectangle var boundingRect = stringWithAttributes.BoundingRectWithSize(new SizeF((int)dimensions.Width, (int)dimensions.Height), NSStringDrawingOptions.UsesLineFragmentOrigin); if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; // Restore our alignment before drawing - see notes above. nsparagraphStyle.Alignment = textAlign; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Alignment var xOffset = 0.0f; switch (textAlign) { case NSTextAlignment.Left: xOffset = 0; break; case NSTextAlignment.Center: xOffset = (dimensions.Width - boundingRect.Width) / 2.0f; break; case NSTextAlignment.Right: xOffset = dimensions.Width - boundingRect.Width; break; default: break; } // Line alignment var yOffset = (CCVerticalTextAlignment.Top == verticleAlignement || boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to top : (CCVerticalTextAlignment.Bottom == verticleAlignement) ? 0 // align to bottom : (imageHeight - boundingRect.Height) / 2.0f; // align to center //Find the rect that the string will draw into inside the dimensions var drawRect = new RectangleF(xOffset , yOffset , boundingRect.Width , boundingRect.Height); NSImage image = null; try { //Set antialias or not NSGraphicsContext.CurrentContext.ShouldAntialias = textDef.isShouldAntialias; image = new NSImage(new SizeF(imageWidth, imageHeight)); image.LockFocus(); // set a default transform var transform = new NSAffineTransform(); transform.Set(); stringWithAttributes.DrawInRect(drawRect); image.UnlockFocus(); // We will use Texture2D from stream here instead of CCTexture2D stream. var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, image); // Debugging purposes // var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // var fileName = Path.Combine(path, "Label3.png"); // using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) // { // tex.SaveAsPng(stream, imageWidth, imageHeight); // } // Create our texture of the label string. var texture = new CCTexture2D(tex); return(texture); } catch (Exception exc) { CCLog.Log("CCLabel: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace); } finally { // clean up the resources if (image != null) { image.Dispose(); image = null; } if (stringWithAttributes != null) { stringWithAttributes.Dispose(); stringWithAttributes = null; } } return(new CCTexture2D()); }
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 )) { }
public NSAttributedString(string str, NSStringAttributes attributes) : this(str, attributes != null ? attributes.Dictionary : null) { }
public static CGSize StringSize(this string This, NSStringAttributes attributes) { return This.StringSize (attributes == null ? null : attributes.Dictionary); }
public static SCNNode SCBoxNode(string title, CGRect frame, NSColor color, float cornerRadius, bool centered) { NSStringAttributes titleAttributes = null; NSStringAttributes centeredTitleAttributes = null; // create and extrude a bezier path to build the box var path = NSBezierPath.FromRoundedRect(frame, cornerRadius, cornerRadius); path.Flatness = 0.05f; var shape = SCNShape.Create(path, 20); shape.ChamferRadius = 0.0f; var node = SCNNode.Create(); node.Geometry = shape; // create an image and fill with the color and text var textureSize = new CGSize(); textureSize.Width = NMath.Ceiling(frame.Size.Width * 1.5f); textureSize.Height = NMath.Ceiling(frame.Size.Height * 1.5f); var texture = new NSImage(textureSize); texture.LockFocus(); var drawFrame = new CGRect(0, 0, textureSize.Width, textureSize.Height); nfloat hue, saturation, brightness, alpha; (color.UsingColorSpace(NSColorSpace.DeviceRGBColorSpace)).GetHsba(out hue, out saturation, out brightness, out alpha); var lightColor = NSColor.FromDeviceHsba(hue, saturation - 0.2f, brightness + 0.3f, alpha); lightColor.Set(); NSGraphics.RectFill(drawFrame); NSBezierPath fillpath = null; if (cornerRadius == 0 && centered == false) { //special case for the "labs" slide drawFrame.Offset(0, -2); fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius); } else { drawFrame.Inflate(-3, -3); fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius); } color.Set(); fillpath.Fill(); // draw the title if any if (title != null) { if (titleAttributes == null) { var paraphStyle = new NSMutableParagraphStyle(); paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping; paraphStyle.Alignment = NSTextAlignment.Center; paraphStyle.MinimumLineHeight = 38; paraphStyle.MaximumLineHeight = 38; var font = NSFont.FromFontName("Myriad Set Semibold", 34) != null?NSFont.FromFontName("Myriad Set Semibold", 34) : NSFont.FromFontName("Avenir Medium", 34); var shadow = new NSShadow(); shadow.ShadowOffset = new CGSize(0, -2); shadow.ShadowBlurRadius = 4; shadow.ShadowColor = NSColor.FromDeviceWhite(0.0f, 0.5f); titleAttributes = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, Shadow = shadow, ParagraphStyle = paraphStyle }; var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy(); centeredParaphStyle.Alignment = NSTextAlignment.Center; centeredTitleAttributes = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, Shadow = shadow, ParagraphStyle = paraphStyle }; } var attrString = new NSAttributedString(title, centered ? centeredTitleAttributes : titleAttributes); var textSize = attrString.Size; //check if we need two lines to draw the text var twoLines = title.Contains("\n"); if (!twoLines) { twoLines = textSize.Width > frame.Size.Width && title.Contains(" "); } //if so, we need to adjust the size to center vertically if (twoLines) { textSize.Height += 38; } if (!centered) { drawFrame.Inflate(-15, 0); } //center vertically var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f; var drawFrameHeight = drawFrame.Size.Height; drawFrame.Size = new CGSize(drawFrame.Size.Width, drawFrame.Size.Height - dy); attrString.DrawString(drawFrame); } texture.UnlockFocus(); //set the created image as the diffuse texture of our 3D box var front = SCNMaterial.Create(); front.Diffuse.Contents = texture; front.LocksAmbientWithDiffuse = true; //use a lighter color for the chamfer and sides var sides = SCNMaterial.Create(); sides.Diffuse.Contents = lightColor; node.Geometry.Materials = new SCNMaterial[] { front, sides, sides, sides, sides }; return(node); }
public static void DrawAtPoint(this string This, CGPoint point, NSStringAttributes attributes) { This.DrawAtPoint (point, attributes == null ? null : attributes.Dictionary); }
// Create the set of display lists for the bitmaps bool MakeGLDisplayListFirst(char first, int count, int baseDL) { int curListIndex; NSColor blackColor; NSStringAttributes attribDict; int dListNum; NSString currentChar; char currentUnichar; CGSize charSize; CGRect charRect = CGRect.Empty; NSImage theImage; bool retval; // Make sure the list isn't already under construction GL.GetInteger(GetPName.ListIndex, out curListIndex); if (curListIndex != 0) { Console.WriteLine("Display list already under construction"); return(false); } // Save pixel unpacking state GL.PushClientAttrib(ClientAttribMask.ClientPixelStoreBit); GL.PixelStore(PixelStoreParameter.UnpackSwapBytes, 0); GL.PixelStore(PixelStoreParameter.UnpackLsbFirst, 0); GL.PixelStore(PixelStoreParameter.UnpackSkipPixels, 0); GL.PixelStore(PixelStoreParameter.UnpackSkipRows, 0); GL.PixelStore(PixelStoreParameter.UnpackRowLength, 0); GL.PixelStore(PixelStoreParameter.UnpackAlignment, 0); blackColor = NSColor.Black; attribDict = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, BackgroundColor = blackColor }; theImage = new NSImage(new CGSize(0, 0)); retval = true; for (dListNum = baseDL, currentUnichar = first; currentUnichar < first + count; dListNum++, currentUnichar++) { currentChar = new NSString(Char.ToString(currentUnichar)); charSize = currentChar.StringSize(attribDict); charRect.Size = charSize; charRect = charRect.Integral(); if (charRect.Size.Width > 0 && charRect.Size.Height > 0) { theImage.Size = charRect.Size; theImage.LockFocus(); NSGraphicsContext.CurrentContext.ShouldAntialias = false; blackColor.Set(); NSBezierPath.FillRect(charRect); currentChar.DrawString(charRect, attribDict.Dictionary); theImage.UnlockFocus(); if (!MakeDisplayList(dListNum, theImage)) { retval = false; break; } } } return(retval); }
// Create the set of display lists for the bitmaps bool MakeGLDisplayListFirst (char first, int count, int baseDL) { int curListIndex; NSColor blackColor; NSStringAttributes attribDict; int dListNum; NSString currentChar; char currentUnichar; CGSize charSize; CGRect charRect = CGRect.Empty; NSImage theImage; bool retval; // Make sure the list isn't already under construction GL.GetInteger (GetPName.ListIndex, out curListIndex); if (curListIndex != 0) { Console.WriteLine ("Display list already under construction"); return false; } // Save pixel unpacking state GL.PushClientAttrib (ClientAttribMask.ClientPixelStoreBit); GL.PixelStore (PixelStoreParameter.UnpackSwapBytes, 0); GL.PixelStore (PixelStoreParameter.UnpackLsbFirst, 0); GL.PixelStore (PixelStoreParameter.UnpackSkipPixels, 0); GL.PixelStore (PixelStoreParameter.UnpackSkipRows, 0); GL.PixelStore (PixelStoreParameter.UnpackRowLength, 0); GL.PixelStore (PixelStoreParameter.UnpackAlignment, 0); blackColor = NSColor.Black; attribDict = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, BackgroundColor = blackColor }; theImage = new NSImage (new CGSize (0,0)); retval = true; for (dListNum = baseDL, currentUnichar = first; currentUnichar < first + count; dListNum++, currentUnichar++) { currentChar = new NSString (Char.ToString (currentUnichar)); charSize = currentChar.StringSize (attribDict); charRect.Size = charSize; charRect = charRect.Integral (); if (charRect.Size.Width > 0 && charRect.Size.Height > 0) { theImage.Size = charRect.Size; theImage.LockFocus (); NSGraphicsContext.CurrentContext.ShouldAntialias = false; blackColor.Set (); NSBezierPath.FillRect (charRect); currentChar.DrawString (charRect, attribDict.Dictionary); theImage.UnlockFocus (); if (!MakeDisplayList(dListNum, theImage)) { retval = false; break; } } } return retval; }
private void UpdateSessionStatusInfo(AccountStatus sessionStatus) { InvokeOnMainThread(() => { try { GuiNotificationButtonBottom.Hidden = true; if (sessionStatus == null) { return; } if (!sessionStatus.IsActive) { string part1 = LocalizedStrings.Instance.LocalizedString("Label_SubscriptionExpired"); if (sessionStatus.IsOnFreeTrial) { part1 = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialExpired"); } string part2 = LocalizedStrings.Instance.LocalizedString("Label_AccountExpiredUpgradeNow"); string title = part1 + " " + part2; CustomButtonStyles.ApplyStyleInfoButton(GuiNotificationButtonBottom, title, NSImage.ImageNamed("iconStatusBad")); NSMutableAttributedString attrTitle = new NSMutableAttributedString(title); NSStringAttributes stringAttributes0 = new NSStringAttributes(); stringAttributes0.Font = GuiNotificationButtonBottom.TitleFont; stringAttributes0.ForegroundColor = GuiNotificationButtonBottom.TitleForegroundColor; stringAttributes0.ParagraphStyle = new NSMutableParagraphStyle { Alignment = NSTextAlignment.Center }; NSStringAttributes stringAttributes1 = new NSStringAttributes(); stringAttributes1.ForegroundColor = NSColor.FromRgb(59, 159, 230); attrTitle.AddAttributes(stringAttributes0, new NSRange(0, title.Length)); attrTitle.AddAttributes(stringAttributes1, new NSRange(title.Length - part2.Length, part2.Length)); GuiNotificationButtonBottom.TitleTextAttributedString = attrTitle; GuiNotificationButtonBottom.Hidden = false; } else { if (sessionStatus.WillAutoRebill) { return; } if ((sessionStatus.ActiveUtil - DateTime.Now).TotalMilliseconds < TimeSpan.FromDays(4).TotalMilliseconds) { int daysLeft = (int)(sessionStatus.ActiveUtil - DateTime.Now).TotalDays; if (daysLeft < 0) { daysLeft = 0; } string notificationString; if (daysLeft == 0) { notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_LastDay"); if (sessionStatus.IsOnFreeTrial) { notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_LastDay"); } } else if (daysLeft == 1) { notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_OneDay"); if (sessionStatus.IsOnFreeTrial) { notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_OneDay"); } } else { notificationString = LocalizedStrings.Instance.LocalizedString("Label_AccountDaysLeft_PARAMETRIZED"); if (sessionStatus.IsOnFreeTrial) { notificationString = LocalizedStrings.Instance.LocalizedString("Label_FreeTrialDaysLeft_PARAMETRIZED"); } notificationString = string.Format(notificationString, daysLeft); } CustomButtonStyles.ApplyStyleInfoButton(GuiNotificationButtonBottom, notificationString, NSImage.ImageNamed("iconStatusModerate")); GuiNotificationButtonBottom.Hidden = false; } } } catch (Exception ex) { Logging.Info(string.Format("{0}", ex)); GuiNotificationButtonBottom.Hidden = true; } }); }
private void UpdateWiFiInfoGuiData() { if (!NSThread.IsMain) { InvokeOnMainThread(() => UpdateWiFiInfoGuiData()); return; } try { UpdateToDoLabelHiddenStatus(); WifiState state = __MainViewModel.WiFiState; if (__MainViewModel.Settings.IsNetworkActionsEnabled == false) { GuiWiFiButton.Hidden = true; GuiNetworkActionPopUpBtn.Hidden = true; return; } NSFont wifiLabelFont = UIUtils.GetSystemFontOfSize(14, NSFontWeight.Thin); if (state == null || string.IsNullOrEmpty(state.Network.SSID)) { GuiWiFiButton.AttributedTitle = AttributedString.Create(LocalizedStrings.Instance.LocalizedString("Label_NoWiFiConnection"), NSColor.SystemGrayColor, NSTextAlignment.Center, wifiLabelFont); GuiWiFiButton.Image = null; GuiWiFiButton.Enabled = false; GuiWiFiButton.Hidden = false; GuiNetworkActionPopUpBtn.Hidden = true; } else { if (state.ConnectedToInsecureNetwork) { GuiWiFiButton.Image = NSImage.ImageNamed("iconWiFiSmallRed"); string networkName = " " + state.Network.SSID + " "; string fullText = networkName + "(" + LocalizedStrings.Instance.LocalizedString("Label_InsecureWiFiConnection") + ") "; NSMutableAttributedString attrTitle = new NSMutableAttributedString(fullText); NSStringAttributes stringAttributes0 = new NSStringAttributes(); stringAttributes0.ForegroundColor = __ToDoDescriptionTextColor; stringAttributes0.Font = wifiLabelFont; NSStringAttributes stringAttributes1 = new NSStringAttributes(); stringAttributes1.ForegroundColor = NSColor.SystemRedColor; stringAttributes1.Font = wifiLabelFont; attrTitle.AddAttributes(stringAttributes0, new NSRange(0, networkName.Length)); attrTitle.AddAttributes(stringAttributes1, new NSRange(networkName.Length, fullText.Length - networkName.Length)); attrTitle.SetAlignment(NSTextAlignment.Center, new NSRange(0, fullText.Length)); GuiWiFiButton.AttributedTitle = attrTitle; } else { GuiWiFiButton.Image = NSImage.ImageNamed("iconWiFiSmallBlue"); GuiWiFiButton.AttributedTitle = AttributedString.Create(" " + state.Network.SSID, __ToDoDescriptionTextColor, NSTextAlignment.Center, wifiLabelFont); } RecreateNetworkActionsButtonItems(); GuiWiFiButton.Enabled = true; GuiWiFiButton.Hidden = false; GuiNetworkActionPopUpBtn.Hidden = false; } } catch (Exception ex) { GuiWiFiButton.Hidden = true; GuiNetworkActionPopUpBtn.Hidden = true; Logging.Info($"{ex}"); } }
private NSStringAttributes GetAttributes() { var attributes = new NSStringAttributes(); var font = NSFontHelper.TryGetFont((float)FontSize, FontWeight, FontStyle, FontFamily); attributes.Font = font; attributes.ForegroundColor = Brush.GetColorWithOpacity(Foreground, Colors.Transparent).Value; if (TextDecorations != TextDecorations.None) { attributes.UnderlineStyle = (int)((TextDecorations & TextDecorations.Underline) == TextDecorations.Underline ? NSUnderlineStyle.Single : NSUnderlineStyle.None); attributes.StrikethroughStyle = (int)((TextDecorations & TextDecorations.Strikethrough) == TextDecorations.Strikethrough ? NSUnderlineStyle.Single : NSUnderlineStyle.None); } var paragraphStyle = new NSMutableParagraphStyle() { MinimumLineHeight = (nfloat)LineHeight, Alignment = TextAlignment.ToNativeTextAlignment(), LineBreakMode = GetLineBreakMode(), }; // For unknown reasons, the LineBreakMode must be set to WordWrap // when applied to a NSTextStorage for text to wrap. if (UseLayoutManager) { paragraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping; } if (LineStackingStrategy != LineStackingStrategy.MaxHeight) { paragraphStyle.MaximumLineHeight = (nfloat)LineHeight; } attributes.ParagraphStyle = paragraphStyle; if (LineHeight != 0 && font != null) { // iOS puts text at the bottom of the line box, whereas Windows puts it at the top. // Empirically this offset gives similar positioning to Windows. // Note: Descender is typically a negative value. var verticalOffset = LineHeight - font.XHeight /* MACOS TODO XHeight ? */ + font.Descender; // Because we're trying to move the text up (toward the top of the line box), // we only set BaselineOffset to a positive value. // A negative value indicates that the the text is already bottom-aligned. attributes.BaselineOffset = Math.Max(0, (float)verticalOffset); } if (CharacterSpacing != 0) { //CharacterSpacing is in 1/1000 of an em, iOS KerningAdjustment is in points. 1 em = 12 points attributes.KerningAdjustment = (CharacterSpacing / 1000f) * 12; } return(attributes); }
public static SCNNode SCBoxNode (string title, CGRect frame, NSColor color, float cornerRadius, bool centered) { NSStringAttributes titleAttributes = null; NSStringAttributes centeredTitleAttributes = null; // create and extrude a bezier path to build the box var path = NSBezierPath.FromRoundedRect (frame, cornerRadius, cornerRadius); path.Flatness = 0.05f; var shape = SCNShape.Create (path, 20); shape.ChamferRadius = 0.0f; var node = SCNNode.Create (); node.Geometry = shape; // create an image and fill with the color and text var textureSize = new CGSize (); textureSize.Width = NMath.Ceiling (frame.Size.Width * 1.5f); textureSize.Height = NMath.Ceiling (frame.Size.Height * 1.5f); var texture = new NSImage (textureSize); texture.LockFocus (); var drawFrame = new CGRect (0, 0, textureSize.Width, textureSize.Height); nfloat hue, saturation, brightness, alpha; (color.UsingColorSpace (NSColorSpace.DeviceRGBColorSpace)).GetHsba (out hue, out saturation, out brightness, out alpha); var lightColor = NSColor.FromDeviceHsba (hue, saturation - 0.2f, brightness + 0.3f, alpha); lightColor.Set (); NSGraphics.RectFill (drawFrame); NSBezierPath fillpath = null; if (cornerRadius == 0 && centered == false) { //special case for the "labs" slide drawFrame.Offset (0, -2); fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius); } else { drawFrame.Inflate (-3, -3); fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius); } color.Set (); fillpath.Fill (); // draw the title if any if (title != null) { if (titleAttributes == null) { var paraphStyle = new NSMutableParagraphStyle (); paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping; paraphStyle.Alignment = NSTextAlignment.Center; paraphStyle.MinimumLineHeight = 38; paraphStyle.MaximumLineHeight = 38; var font = NSFont.FromFontName ("Myriad Set Semibold", 34) != null ? NSFont.FromFontName ("Myriad Set Semibold", 34) : NSFont.FromFontName ("Avenir Medium", 34); var shadow = new NSShadow (); shadow.ShadowOffset = new CGSize (0, -2); shadow.ShadowBlurRadius = 4; shadow.ShadowColor = NSColor.FromDeviceWhite (0.0f, 0.5f); titleAttributes = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, Shadow = shadow, ParagraphStyle = paraphStyle }; var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy (); centeredParaphStyle.Alignment = NSTextAlignment.Center; centeredTitleAttributes = new NSStringAttributes { Font = font, ForegroundColor = NSColor.White, Shadow = shadow, ParagraphStyle = paraphStyle }; } var attrString = new NSAttributedString (title, centered ? centeredTitleAttributes : titleAttributes); var textSize = attrString.Size; //check if we need two lines to draw the text var twoLines = title.Contains ("\n"); if (!twoLines) twoLines = textSize.Width > frame.Size.Width && title.Contains (" "); //if so, we need to adjust the size to center vertically if (twoLines) textSize.Height += 38; if (!centered) drawFrame.Inflate (-15, 0); //center vertically var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f; var drawFrameHeight = drawFrame.Size.Height; drawFrame.Size = new CGSize (drawFrame.Size.Width, drawFrame.Size.Height - dy); attrString.DrawString (drawFrame); } texture.UnlockFocus (); //set the created image as the diffuse texture of our 3D box var front = SCNMaterial.Create (); front.Diffuse.Contents = texture; front.LocksAmbientWithDiffuse = true; //use a lighter color for the chamfer and sides var sides = SCNMaterial.Create (); sides.Diffuse.Contents = lightColor; node.Geometry.Materials = new SCNMaterial[] { front, sides, sides, sides, sides }; return node; }
public static void DrawInRect(this string This, CGRect rect, NSStringAttributes attributes) { This.DrawInRect (rect, attributes == null ? null : attributes.Dictionary); }
public override void DrawRect(CGRect dirtyRect) { base.DrawRect(dirtyRect); var attributes = new NSStringAttributes { ForegroundColor = NSColor.Blue, Font = NSFont.FromFontName("Andale Mono", 14) }; ProcessTextFormat(attributes); NSColor.Black.SetFill(); NSBezierPath.FillRect(dirtyRect); lock (Terminal) { int row = ViewTop; float verticalOffset = -row * (float)CharacterHeight; var lines = Terminal.ViewPort.GetLines(ViewTop, Rows); foreach (var line in lines) { if (line == null) { row++; continue; } int column = 0; var xform = new NSAffineTransform(); xform.Scale((nfloat)(line.DoubleWidth ? 2.0 : 1.0), (nfloat)((line.DoubleHeightTop || line.DoubleHeightBottom) ? 2.0 : 1.0)); xform.Concat(); var spanStart = 0; while (column < line.Count) { bool selected = TextSelection == null ? false : TextSelection.Within(column, row); var backgroundColor = GetBackgroundColor(line[column].Attributes, selected); if (column < (line.Count - 1) && GetBackgroundColor(line[column + 1].Attributes, TextSelection == null ? false : TextSelection.Within(column + 1, row)) == backgroundColor) { column++; continue; } var rect = new CGRect( spanStart * CharacterWidth, ((row - (line.DoubleHeightBottom ? 1 : 0)) * CharacterHeight + verticalOffset) * (line.DoubleHeightBottom | line.DoubleHeightTop ? 0.5 : 1.0), ((column - spanStart + 1) * CharacterWidth) + 0.9, CharacterHeight + 0.9 ); backgroundColor.SetFill(); NSBezierPath.FillRect(rect); column++; spanStart = column; } xform.Invert(); xform.Concat(); row++; } row = ViewTop; foreach (var line in lines) { if (line == null) { row++; continue; } int column = 0; var xform = new NSAffineTransform(); xform.Scale((nfloat)(line.DoubleWidth ? 2.0 : 1.0), (nfloat)((line.DoubleHeightTop || line.DoubleHeightBottom) ? 2.0 : 1.0)); xform.Concat(); var spanStart = 0; string toDisplay = string.Empty; while (column < line.Count) { bool selected = TextSelection == null ? false : TextSelection.Within(column, row); var foregroundColor = GetForegroundColor(line[column].Attributes, selected); toDisplay += line[column].Char.ToString() + line[column].CombiningCharacters; if ( column < (line.Count - 1) && GetForegroundColor(line[column + 1].Attributes, TextSelection == null ? false : TextSelection.Within(column + 1, row)) == foregroundColor && line[column + 1].Attributes.Underscore == line[column].Attributes.Underscore && line[column + 1].Attributes.Reverse == line[column].Attributes.Reverse && line[column + 1].Attributes.Bright == line[column].Attributes.Bright ) { column++; continue; } var textPosition = new CGPoint( spanStart * CharacterWidth, ((row - (line.DoubleHeightBottom ? 1 : 0)) * CharacterHeight + verticalOffset + attributes.Font.Descender) * (line.DoubleHeightBottom | line.DoubleHeightTop ? 0.5 : 1.0) ); attributes.ForegroundColor = foregroundColor; attributes.UnderlineStyle = line[column].Attributes.Underscore ? 1 : 0; var nsStr = new NSString(toDisplay); nsStr.DrawAtPoint(textPosition, attributes.Dictionary); column++; spanStart = column; toDisplay = ""; } xform.Invert(); xform.Concat(); row++; } if (Terminal.CursorState.ShowCursor) { var cursorY = Terminal.ViewPort.TopRow - ViewTop + Terminal.CursorState.CurrentRow; var cursorRect = new CGRect( Terminal.CursorState.CurrentColumn * CharacterWidth, cursorY * CharacterHeight, CharacterWidth + 0.9, CharacterHeight + 0.9 ); var path = NSBezierPath.FromRect(cursorRect); GetForegroundColor(Terminal.CursorState.Attributes, false).Set(); path.Stroke(); } } }
internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition) { if (string.IsNullOrEmpty(text)) return new CCTexture2D(); int imageWidth; int imageHeight; var textDef = textDefinition; var contentScaleFactorWidth = CCLabel.DefaultTexelToContentSizeRatios.Width; var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height; textDef.FontSize *= contentScaleFactorWidth; textDef.Dimensions.Width *= contentScaleFactorWidth; textDef.Dimensions.Height *= contentScaleFactorHeight; //bool hasPremultipliedAlpha; // font NSFont font = null; var ext = System.IO.Path.GetExtension(textDef.FontName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { try { textDef.FontName = LoadFontFile(textDef.FontName); font = NSFont.FromFontName(textDef.FontName, textDef.FontSize); } catch { CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName); } } else { // font font = NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); } if (font == null) { font = NSFontManager.SharedFontManager.FontWithFamily("Arial", NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); CCLog.Log("{0} not found. Defaulting to Arial.", textDef.FontName); } // color var foregroundColor = NSColor.White; // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? NSTextAlignment.Right : (CCTextAlignment.Center == horizontalAlignment) ? NSTextAlignment.Center : NSTextAlignment.Left; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? NSLineBreakMode.CharWrapping : (CCLabelLineBreak.Word == textDef.LineBreak) ? NSLineBreakMode.ByWordWrapping : NSLineBreakMode.Clipping; var nsparagraphStyle = new NSMutableParagraphStyle(); nsparagraphStyle.SetParagraphStyle(NSMutableParagraphStyle.DefaultParagraphStyle); nsparagraphStyle.LineBreakMode = lineBreak; nsparagraphStyle.Alignment = textAlign; // Create a new attributed string definition var nsAttributes = new NSStringAttributes (); // Font attribute nsAttributes.Font = font; nsAttributes.ForegroundColor = foregroundColor; nsAttributes.ParagraphStyle = nsparagraphStyle; var stringWithAttributes = new NSAttributedString(text, nsAttributes); var realDimensions = stringWithAttributes.Size; // Mac crashes if the width or height is 0 if (realDimensions == SizeF.Empty) { CCLog.Log("Native string:", "Dimensions of native NSAttributedString can not be 0,0"); return new CCTexture2D(); } var dimensions = new SizeF(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; // // * Note * This seems to only effect Mac because iOS works fine without this work around. // Right Alignment BoundingRectWithSize does not seem to be working correctly when the following conditions are set: // 1) Alignment Right // 2) No dimensions // 3) There are new line characters embedded in the string. // // So we set alignment to Left, calculate our bounds and then restore alignement afterwards before drawing. // if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; // Set our alignment variables to left - see notes above. nsparagraphStyle.Alignment = NSTextAlignment.Left; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } // Calculate our bounding rectangle var boundingRect = stringWithAttributes.BoundingRectWithSize(new SizeF((int)dimensions.Width, (int)dimensions.Height), NSStringDrawingOptions.UsesLineFragmentOrigin); if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; // Restore our alignment before drawing - see notes above. nsparagraphStyle.Alignment = textAlign; stringWithAttributes.Dispose(); stringWithAttributes = null; stringWithAttributes = new NSAttributedString(text, nsAttributes); } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Alignment var xOffset = 0.0f; switch (textAlign) { case NSTextAlignment.Left: xOffset = 0; break; case NSTextAlignment.Center: xOffset = (dimensions.Width-boundingRect.Width)/2.0f; break; case NSTextAlignment.Right: xOffset = dimensions.Width-boundingRect.Width; break; default: break; } // Line alignment var yOffset = (CCVerticalTextAlignment.Top == verticleAlignement || boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to top : (CCVerticalTextAlignment.Bottom == verticleAlignement) ? 0 // align to bottom : (imageHeight - boundingRect.Height) / 2.0f; // align to center //Find the rect that the string will draw into inside the dimensions var drawRect = new RectangleF(xOffset , yOffset , boundingRect.Width , boundingRect.Height); NSImage image = null; try { //Set antialias or not NSGraphicsContext.CurrentContext.ShouldAntialias = textDef.isShouldAntialias; image = new NSImage(new SizeF(imageWidth, imageHeight)); image.LockFocus(); // set a default transform var transform = new NSAffineTransform(); transform.Set(); stringWithAttributes.DrawInRect(drawRect); image.UnlockFocus(); // We will use Texture2D from stream here instead of CCTexture2D stream. var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, image); // Debugging purposes // var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // var fileName = Path.Combine(path, "Label3.png"); // using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) // { // tex.SaveAsPng(stream, imageWidth, imageHeight); // } // Create our texture of the label string. var texture = new CCTexture2D(tex); return texture; } catch (Exception exc) { CCLog.Log ("CCLabel: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace); } finally { // clean up the resources if (image != null) { image.Dispose (); image = null; } if (stringWithAttributes != null) { stringWithAttributes.Dispose (); stringWithAttributes = null; } } return new CCTexture2D (); }