private Size LayoutTypography(Size size) { if (UseLayoutManager) { if (_textContainer == null) { return(default(Size)); } _textContainer.Size = size; // Required for GetUsedRectForTextContainer to return a value. _layoutManager.GetGlyphRange(_textContainer); return(_layoutManager #if NET6_0_OR_GREATER .GetUsedRect #else .GetUsedRectForTextContainer #endif (_textContainer).Size); } else { if (_attributedString == null) { return(default(Size)); } return(_attributedString.BoundingRectWithSize(size, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size); } }
public void NSAttributedString_BoundingRectWithSize() { NSFont font = NSFont.FromFontName("Arial", 40); NSAttributedString str = new NSAttributedString("Hello World", font); CGRect rect = str.BoundingRectWithSize(new CGSize(20, 30), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); Assert.IsTrue(rect.Width > 0); Assert.IsTrue(rect.Height > 0); }
protected override Size MeasureOverride(Size size) { var hasSameDesiredSize = !_measureInvalidated && _previousAvailableSize != null && _previousDesiredSize.Width == size.Width && _previousDesiredSize.Height == size.Height; var isSingleLineNarrower = !_measureInvalidated && _previousAvailableSize != null && _previousDesiredSize.Width <= size.Width && _previousDesiredSize.Height == size.Height; if (hasSameDesiredSize || isSingleLineNarrower) { return(_previousDesiredSize); } else { _previousAvailableSize = size; _measureInvalidated = false; UpdateTypography(); var horizontalPadding = Padding.Left + Padding.Right; var verticalPadding = Padding.Top + Padding.Bottom; // available size considering padding size.Width -= horizontalPadding; size.Height -= verticalPadding; var result = LayoutTypography(size); if (result.Height == 0) // this can happen when Text is null or empty { // This measures the height correctly, even if the Text is null or empty // This matches Windows where empty TextBlocks still have a height (especially useful when measuring ListView items with no DataContext) var font = NSFontHelper.TryGetFont((float)FontSize * 2, FontWeight, FontStyle, FontFamily); var str = new NSAttributedString(Text, font); var rect = str.BoundingRectWithSize(size, NSStringDrawingOptions.UsesDeviceMetrics); result = new Size(rect.Width, rect.Height); } result.Width += horizontalPadding; result.Height += verticalPadding; return(_previousDesiredSize = new CGSize(Math.Ceiling(result.Width), Math.Ceiling(result.Height))); } }
public Size MeasureText(string text, Font font) { if (string.IsNullOrEmpty(text)) { return(Size.Zero); } if (font == null) { throw new ArgumentNullException("font"); } string fontName = font.Name; Array availableFonts = #if __IOS__ || __TVOS__ UIKit.UIFont.FontNamesForFamilyName(fontName); #else AppKit.NSFontManager.SharedFontManager.AvailableMembersOfFontFamily(fontName).ToArray(); #endif #if __IOS__ || __TVOS__ UIKit.UIFont nsFont; if (availableFonts != null && availableFonts.Length > 0) { nsFont = UIKit.UIFont.FromName(font.Name, (nfloat)font.Size); } else { nsFont = UIKit.UIFont.FromName("Georgia", (nfloat)font.Size); } #else AppKit.NSFont nsFont; if (availableFonts != null && availableFonts.Length > 0) { nsFont = AppKit.NSFont.FromFontName(font.Name, (nfloat)font.Size); } else { nsFont = AppKit.NSFont.FromFontName("Georgia", (nfloat)font.Size); } #endif using (var s = new NSAttributedString(text, font: nsFont)) using (nsFont) { #if __IOS__ || __TVOS__ var result = s.GetBoundingRect(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics, null); #else var result = s.BoundingRectWithSize(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics); #endif return(new Size(result.Width, result.Height)); } }
static nfloat HeightWrappedToWidth(string title, NSFont font) { NSAttributedString textAttrStr = new NSAttributedString(title, font); CGSize maxSize = new CGSize(PUBLICATION_LINT_WIDTH - 6 * 2, 1000); CGRect boundRect = textAttrStr.BoundingRectWithSize(maxSize, NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); //multiple of 17 nfloat stringHeight = boundRect.Height; return(stringHeight); }
public static nfloat HeightWrappedToWidth(string title, nfloat fontSize, nfloat width) { NSAttributedString textAttrStr = new NSAttributedString(title, NSFont.SystemFontOfSize(fontSize)); var maxSize = new CGSize(width, 1000); CGRect boundRect = textAttrStr.BoundingRectWithSize(maxSize, NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); //multiple of 17 nfloat stringHeight = boundRect.Height; return(stringHeight); }
nfloat HeightWrappedToWidth(NSTextField sourceTextField, nfloat fontSize) { NSAttributedString textAttrStr = new NSAttributedString(sourceTextField.StringValue, NSFont.SystemFontOfSize(fontSize)); CGSize maxSize = sourceTextField.Frame.Size; maxSize.Height = 1000; CGRect boundRect = textAttrStr.BoundingRectWithSize(maxSize, NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); nfloat stringHeight = boundRect.Height; nfloat cellHeight = HeightWrappedWidth(sourceTextField, fontSize); return(Math.Max((float)(cellHeight - 5), (float)(stringHeight))); }
protected override Size MeasureOverride(Size size) { // `size` is used to compare with the previous one `_previousDesiredSize` // We need to apply `Math.Ceiling` to compare them correctly var isSameOrNarrower = !_measureInvalidated && _previousAvailableSize != null && _previousDesiredSize.Width <= Math.Ceiling(size.Width) && _previousDesiredSize.Height == Math.Ceiling(size.Height); if (isSameOrNarrower) { return(_previousDesiredSize); } else { _previousAvailableSize = size; _measureInvalidated = false; UpdateTypography(); var padding = Padding; // available size considering padding size = size.Subtract(padding); var result = LayoutTypography(size); if (result.Height == 0) // this can happen when Text is null or empty { // This measures the height correctly, even if the Text is null or empty // This matches Windows where empty TextBlocks still have a height (especially useful when measuring ListView items with no DataContext) var font = NSFontHelper.TryGetFont((float)FontSize * 2, FontWeight, FontStyle, FontFamily); using var str = new NSAttributedString(Text, font); var rect = str.BoundingRectWithSize(size, NSStringDrawingOptions.UsesDeviceMetrics); result = new Size(rect.Width, rect.Height); } result = result.Add(padding); return(_previousDesiredSize = new Size(Math.Ceiling(result.Width), Math.Ceiling(result.Height))); } }
public Size MeasureText(string text, Font font) { if (string.IsNullOrEmpty(text)) return Size.Zero; if (font == null) throw new ArgumentNullException("font"); string fontName = font.Name; Array availableFonts = #if __IOS__ UIKit.UIFont.FontNamesForFamilyName(fontName); #else AppKit.NSFontManager.SharedFontManager.AvailableMembersOfFontFamily (fontName).ToArray (); #endif #if __IOS__ UIKit.UIFont nsFont; if (availableFonts != null && availableFonts.Length > 0) nsFont = UIKit.UIFont.FromName(font.Name, (nfloat)font.Size); else nsFont = UIKit.UIFont.FromName("Georgia", (nfloat)font.Size); #else AppKit.NSFont nsFont; if (availableFonts != null && availableFonts.Length > 0) nsFont = AppKit.NSFont.FromFontName(font.Name, (nfloat)font.Size); else nsFont = AppKit.NSFont.FromFontName("Georgia", (nfloat)font.Size); #endif using (var s = new NSAttributedString(text, font: nsFont)) using (nsFont) { #if __IOS__ var result = s.GetBoundingRect(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics, null); #else var result = s.BoundingRectWithSize(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics); #endif return new Size(result.Width, result.Height); } }
//what's new view nfloat HeightOfWhatNewInfoView() { List <GuideCard> addedGuideCardList = BookInfo.AddedGuideCard; List <GuideCard> delGuideCardList = BookInfo.DeletedGuideCard; List <GuideCard> updateGuideCardList = BookInfo.UpdatedGuideCard; string addString = "GuideCards Added:\n"; if (addedGuideCardList.Count > 0) { foreach (GuideCard guidCard in addedGuideCardList) { if (!string.IsNullOrEmpty(guidCard.Name)) { addString += guidCard.Name + "\n"; } } } else { addString += "No Files Added\n"; } string deleteString = "GuideCards Deleted:\n"; if (delGuideCardList.Count > 0) { foreach (GuideCard guidCard in delGuideCardList) { if (!string.IsNullOrEmpty(guidCard.Name)) { deleteString += guidCard.Name + "\n"; } } } else { deleteString += "No Files Deleted\n"; } string updateString = "GuideCards Updated:\n"; if (updateGuideCardList.Count > 0) { foreach (GuideCard guidCard in updateGuideCardList) { if (!string.IsNullOrEmpty(guidCard.Name)) { updateString += guidCard.Name + "\n"; } } } else { updateString += "No Files Updated"; } String infoString = addString + deleteString + updateString; WhatNewInfoLabel.StringValue = infoString; NSAttributedString textAttrStr = new NSAttributedString(infoString, NSFont.SystemFontOfSize(13)); CGSize maxSize = new CGSize(430, 1000); CGRect boundRect = textAttrStr.BoundingRectWithSize(maxSize, NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); //multiple of 17 nfloat stringHeight = boundRect.Height; return(stringHeight); }
public Size MeasureText(string text, Font font) { if (string.IsNullOrEmpty(text)) return Size.Zero; if (font == null) throw new ArgumentNullException("font"); #if __IOS__ UIKit.UIFont nsFont = UIKit.UIFont.FromName("Georgia", (nfloat)font.Size); #else AppKit.NSFont nsFont = AppKit.NSFont.FromFontName("Georgia", (nfloat)font.Size); #endif using (var s = new NSAttributedString(text, font: nsFont)) using (nsFont) { #if __IOS__ var result = s.GetBoundingRect(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics, null); #else var result = s.BoundingRectWithSize(new CGSize(float.MaxValue, float.MaxValue), NSStringDrawingOptions.UsesDeviceMetrics); #endif return new Size(result.Width, result.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 *= (int)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 (Exception exc) { 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 fontColor = textDef.FontFillColor; var fontAlpha = textDef.FontAlpha; var foregroundColor = NSColor.FromDeviceRgba(fontColor.R / 255.0f, fontColor.G / 255.0f, fontColor.B / 255.0f, fontAlpha / 255.0f); // 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) { throw new ArgumentOutOfRangeException("Native string:", "Dimensions of native NSAttributedString can not be 0,0"); } 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; } 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; } 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); //Disable antialias NSGraphicsContext.CurrentContext.ShouldAntialias = false; NSImage 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); }