public Task <UIImage> LoadImageAsync( ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { UIImage image = null; var fontsource = imagesource as FontImageSource; if (fontsource != null) { // This will allow lookup from the Embedded Fonts var font = Font.OfSize(fontsource.FontFamily, fontsource.Size).ToUIFont(); var iconcolor = fontsource.Color ?? _defaultColor; var attString = new NSAttributedString(fontsource.Glyph, font: font, foregroundColor: iconcolor.ToUIColor()); var imagesize = ((NSString)fontsource.Glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _)); UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx); attString.DrawString(new RectangleF( imagesize.Width / 2 - boundingRect.Size.Width / 2, imagesize.Height / 2 - boundingRect.Size.Height / 2, imagesize.Width, imagesize.Height)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (image != null && iconcolor != _defaultColor) { image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); } } return(Task.FromResult(image)); }
private Size LayoutTypography(Size size) { if (UseLayoutManager) { if (_textContainer == null) { return(default(Size)); } _textContainer.Size = size; #if NET6_0_OR_GREATER return(_layoutManager.GetUsedRect #else return _layoutManager.GetUsedRectForTextContainer #endif (_textContainer).Size); } else { if (_attributedString == null) { return(default(Size)); } return(_attributedString.GetBoundingRect(size, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size); } }
internal UIImage RenderImage(IFontImageSource imageSource, float scale) { var font = FontManager.GetFont(imageSource.Font); var color = (imageSource.Color ?? Colors.White).ToPlatform(); var glyph = (NSString)imageSource.Glyph; var attString = new NSAttributedString(glyph, font, color); var imagesize = glyph.GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _)); UIGraphics.BeginImageContextWithOptions(imagesize, false, scale); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, 0, ctx); attString.DrawString(new CGRect( imagesize.Width / 2 - boundingRect.Size.Width / 2, imagesize.Height / 2 - boundingRect.Size.Height / 2, imagesize.Width, imagesize.Height)); var image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)); }
public Task <UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default, float scale = 1) { UIImage image = null; if (imagesource is IconImageSource iconsource && IconFontRegistry.Instance.TryFindIconForKey(iconsource.Name, out var icon)) { var iconcolor = iconsource.Color.IsDefault ? _defaultColor : iconsource.Color; var imagesize = new SizeF((float)iconsource.Size, (float)iconsource.Size); var font = UIFont.FromName(icon.FontFamily ?? string.Empty, (float)iconsource.Size) ?? UIFont.SystemFontOfSize((float)iconsource.Size); UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f); var attString = new NSAttributedString(icon.Glyph, font: font, foregroundColor: iconcolor.ToUIColor()); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx); attString.DrawString(new RectangleF( (imagesize.Width / 2) - (boundingRect.Size.Width / 2), (imagesize.Height / 2) - (boundingRect.Size.Height / 2), imagesize.Width, imagesize.Height)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (iconcolor != _defaultColor) { image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); } } return(Task.FromResult(image)); }
public Task <UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default, float scale = 1) { UIImage image = null; if (imagesource is IconImageSource iconsource && FontRegistry.HasFont(iconsource.Name, out var font)) { // This will allow lookup from the Embedded Fonts var glyph = font.GetGlyph(iconsource.Name); var cleansedname = FontExtensions.CleanseFontName(font.Alias); var uifont = UIFont.FromName(cleansedname ?? string.Empty, (float)iconsource.Size) ?? UIFont.SystemFontOfSize((float)iconsource.Size); var iconcolor = iconsource.Color.IsDefault ? _defaultColor : iconsource.Color; var attString = new NSAttributedString(glyph, font: uifont, foregroundColor: iconcolor.ToUIColor()); var imagesize = ((NSString)glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _)); UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx); attString.DrawString(new RectangleF( (imagesize.Width / 2) - (boundingRect.Size.Width / 2), (imagesize.Height / 2) - (boundingRect.Size.Height / 2), imagesize.Width, imagesize.Height)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (image != null && iconcolor != _defaultColor) { image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); } } return(Task.FromResult(image)); }
public void UpdatePreferredSize(float maxWidth) { var text = this.String; if (string.IsNullOrEmpty(text)) { preferredSize = CGSize.Empty; return; } // TODO: test .Font property var fontName = this.WeakFont as string; if (fontName == null) { Console.WriteLine("Trying to update label size without font"); preferredSize = CGSize.Empty; return; } if (font == null) { font = UIFont.FromName(fontName, UIFont.ButtonFontSize); } var attributes = new UIStringAttributes { Font = font }; var nsString = new NSAttributedString(text, attributes); var fontBounds = nsString.GetBoundingRect(new CGSize(maxWidth, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null); fontBounds.Size = new CGSize(fontBounds.Size.Width, fontBounds.Size.Height + Math.Abs(font.Descender)); preferredSize = fontBounds.Size; }
public Task <UIImage> LoadImageAsync( ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { UIImage image = null; var fontsource = imagesource as FontImageSource; if (fontsource != null) { var iconcolor = fontsource.Color != Color.Default ? fontsource.Color : Color.White; var imagesize = new SizeF((float)fontsource.Size, (float)fontsource.Size); var font = UIFont.FromName(fontsource.FontFamily ?? string.Empty, (float)fontsource.Size) ?? UIFont.SystemFontOfSize((float)fontsource.Size); UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f); var attString = new NSAttributedString(fontsource.Glyph, font: font, foregroundColor: iconcolor.ToUIColor()); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx); attString.DrawString(new RectangleF( imagesize.Width / 2 - boundingRect.Size.Width / 2, imagesize.Height / 2 - boundingRect.Size.Height / 2, imagesize.Width, imagesize.Height)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); if (iconcolor != Color.Default) { image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); } } return(Task.FromResult(image)); }
private Size LayoutTypography(Size size) { if (UseLayoutManager) { _textContainer.Size = size; return(_layoutManager.GetUsedRectForTextContainer(_textContainer).Size); } else { return(_attributedString.GetBoundingRect(size, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size); } }
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)); } }
/// <summary> /// Gets the string bound rect. /// </summary> /// <returns>The string bound rect.</returns> /// <param name="text">Text.</param> /// <param name="font">Font.</param> /// <param name="maxSize">Max size.</param> public static CGSize GetStringBoundRect(string text, UIFont font, CGSize maxSize) { if (text != null && font != null) { NSAttributedString textAttrStr = new NSAttributedString(text, font); CGRect boundRect = textAttrStr.GetBoundingRect(maxSize, NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null); return(new CGSize(Math.Ceiling(boundRect.Size.Width), Math.Ceiling(boundRect.Size.Height))); } return(new CGSize(0, 0)); }
public static UIImage DrawTextInImage1(UIImage uiImage, NSString text, NSString text1, CGPoint point) { nfloat fWidth = uiImage.Size.Width; nfloat fHeight = uiImage.Size.Height; nfloat afHeight = uiImage.Size.Height / 5; UIFont font = UIFont.BoldSystemFontOfSize(50); UIFont authorfont = UIFont.SystemFontOfSize(45); var imagesize = new CGSize(fWidth, fHeight + afHeight); UIGraphics.BeginImageContext(imagesize); UIImage background = new UIImage(); background.Draw(new CGRect(0, 0, fWidth, fHeight + afHeight)); uiImage.Draw(new CGRect(0, 0, fWidth, fHeight)); var style = new NSMutableParagraphStyle(); style.Alignment = UITextAlignment.Center; var att = new NSAttributedString(text, font: font, paragraphStyle: style, foregroundColor: UIColor.White ); var author = new NSAttributedString(text1, font: authorfont, paragraphStyle: style, foregroundColor: UIColor.Black ); CGRect stringrect = att.GetBoundingRect(new CGSize(fWidth - 100, fHeight + afHeight), NSStringDrawingOptions.UsesLineFragmentOrigin, null); System.Diagnostics.Debug.WriteLine("width:" + stringrect.Size.Width + " height:" + stringrect.Size.Height); nfloat yOffset = (fHeight - stringrect.Size.Height) / 2; nfloat heightsize = stringrect.Size.Height + yOffset; System.Diagnostics.Debug.WriteLine("yOffset + height:" + heightsize); CGRect rect = new CGRect(point.X + 50, yOffset, fWidth - 100, fHeight + afHeight); att.DrawString(rect.Integral()); CGRect rect1 = new CGRect(point.X, fHeight + (afHeight - authorfont.LineHeight) / 2, fWidth, 50); author.DrawString(rect1.Integral()); UIImage resultImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return(resultImage); }
public static UIImage ConvertFontIconToUIImage(string fontFamily, double fontSize, UIColor iconcolor, string glyph) { UIImage image = null; var cleansedname = CleanseFontName(fontFamily); var font = UIFont.FromName(cleansedname ?? string.Empty, (float)fontSize) ?? UIFont.SystemFontOfSize((float)fontSize); var attString = new NSAttributedString(glyph, font: font, foregroundColor: iconcolor); var imagesize = ((NSString)glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _)); UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f); var ctx = new NSStringDrawingContext(); var boundingRect = attString.GetBoundingRect(imagesize, 0, ctx); attString.DrawString(new DrawRect((float)(imagesize.Width / 2 - boundingRect.Size.Width / 2), (float)(imagesize.Height / 2 - boundingRect.Size.Height / 2), (float)imagesize.Width, (float)imagesize.Height)); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return(image); }
public static UIImage ToUIImage(this IIcon icon, nfloat size) { var attributedString = new NSAttributedString($"{icon.Character}", new CTStringAttributes { Font = new CTFont(Iconize.FindModuleOf(icon).FontName, size), ForegroundColorFromContext = true }); var boundSize = attributedString.GetBoundingRect(new CGSize(10000, 10000), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f); attributedString.DrawString(new CGRect(0, 0, boundSize.Width, boundSize.Height)); var image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return image; }
/// <summary> /// To the UI image. /// </summary> /// <param name="iconChar">The character value for the desired icon.</param> /// <param name="size">The size.</param> /// <returns></returns> private UIImage GetUIImage(char iconChar, nfloat size) { var attributedString = new NSAttributedString($"{iconChar}", new CTStringAttributes { Font = new CTFont(FontAwesomeRegular.FontName, size), ForegroundColorFromContext = true }); var boundSize = attributedString.GetBoundingRect(new CGSize(10000f, 10000f), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f); attributedString.DrawString(new CGRect(0f, 0f, boundSize.Width, boundSize.Height)); using (var image = UIGraphics.GetImageFromCurrentImageContext()) { UIGraphics.EndImageContext(); return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)); } }
CGSize LabelSize(double widthConstraint, nfloat fontSize) { var font = UIFont.FromDescriptor(FontDescriptor, fontSize); CGSize labelSize = CGSize.Empty; var constraintSize = new CGSize(widthConstraint, double.PositiveInfinity); if (Element?.F9PFormattedString != null) { ControlAttributedText = Element.F9PFormattedString.ToNSAttributedString(font, ControlTextColor);//, twice: twice); labelSize = ControlAttributedText.GetBoundingRect(constraintSize, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; ControlText = null; } else if (ControlText != null) { labelSize = ControlText.StringSize(font, constraintSize, (Element.LineBreakMode == LineBreakMode.CharacterWrap ? UILineBreakMode.CharacterWrap : UILineBreakMode.WordWrap)); ControlAttributedText = null; } return(labelSize); }
/// <summary> /// To the UI image. /// </summary> /// <param name="icon">The icon.</param> /// <param name="size">The size.</param> /// <returns></returns> public static UIImage ToUIImage(this IIcon icon, nfloat size) { var attributedString = new NSAttributedString($"{icon.Character}", new CTStringAttributes { Font = new CTFont(IconFonts.FindModuleOf(icon).FontName, size), ForegroundColorFromContext = true }); var boundSize = attributedString.GetBoundingRect(new CGSize(10000f, 10000f), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f); attributedString.DrawString(new CGRect(0f, 0f, boundSize.Width, boundSize.Height)); using (var image = UIGraphics.GetImageFromCurrentImageContext()) { UIGraphics.EndImageContext(); return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)); } }
private float HeightOfText(string text,int width) { UIFont font = UIFont.SystemFontOfSize(15.0f); NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle(); paragraphStyle.LineBreakMode = UILineBreakMode.WordWrap; NSMutableDictionary attributes = new NSMutableDictionary(); attributes[UIStringAttributeKey.Font] = font; attributes[UIStringAttributeKey.ParagraphStyle] = paragraphStyle; NSAttributedString attributedText = new NSAttributedString (text, attributes); RectangleF paragraphRect = attributedText.GetBoundingRect( new System.Drawing.SizeF(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null); return paragraphRect.Height; }
private float HeightOfText(string text, int width) { UIFont font = UIFont.SystemFontOfSize(15.0f); NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle(); paragraphStyle.LineBreakMode = UILineBreakMode.WordWrap; NSMutableDictionary attributes = new NSMutableDictionary(); attributes[UIStringAttributeKey.Font] = font; attributes[UIStringAttributeKey.ParagraphStyle] = paragraphStyle; NSAttributedString attributedText = new NSAttributedString(text, attributes); RectangleF paragraphRect = attributedText.GetBoundingRect( new System.Drawing.SizeF(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, null); return(paragraphRect.Height); }
public override void DrawText(CGRect rect) { var attributes = new Dictionary <NSString, NSObject> { { new NSString(""), null } }; var attributes2 = new NSDictionary <NSString, NSObject>(new NSString(UIStringAttributeKey.Font), Font); var attributedText = new NSAttributedString(Text ?? new NSString(""), attributes2); CGSize size = rect.Size; size.Height = attributedText.GetBoundingRect(size, NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size.Height; if (Lines != 0) { size.Height = ( nfloat )Math.Min(size.Height, Lines * Font.LineHeight); } rect.Size = size; base.DrawText(rect); }
public override void Draw(CGRect rect) { var color = Color.CGColor.Components; UIGraphics.BeginImageContext(new CGSize(30, 20)); var ctx = UIGraphics.GetCurrentContext(); ctx.SetFillColor(color[0], color[1], color[2], 1); ctx.SetShadow(CGSize.Empty, 7f, UIColor.Black.CGColor); ctx.AddLines(new[] { new CGPoint(15, 5), new CGPoint(25, 25), new CGPoint(5, 25) }); ctx.ClosePath(); ctx.FillPath(); var viewImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); var imgframe = new CGRect(ShowOnRect.X + (ShowOnRect.Width - 30) / 2, ShowOnRect.Height / 2 + ShowOnRect.Y, 30, 13); var img = new UIImageView(viewImage); AddSubview(img); img.TranslatesAutoresizingMaskIntoConstraints = false; var dict = new NSDictionary("img", img); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat($@"H:|-{imgframe.X.ToString(CultureInfo.InvariantCulture)}-[img({imgframe.Width.ToString(CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat($@"V:|-{imgframe.Y.ToString(CultureInfo.InvariantCulture)}-[img({imgframe.Height.ToString(CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); var font = UIFont.FromName(FontName, FontSize); var message = new NSAttributedString(Message, font); var size = message.GetBoundingRect(new CGSize(FieldFrame.Width - PaddingInErrorPopUp * 2, 1000), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; size = new CGSize((nfloat)Math.Ceiling(size.Width), (nfloat)Math.Ceiling(size.Height)); var view = new UIView(CGRect.Empty); InsertSubviewBelow(view, img); view.BackgroundColor = Color; view.Layer.CornerRadius = 5f; view.Layer.ShadowColor = UIColor.Black.CGColor; view.Layer.ShadowRadius = 5f; view.Layer.Opacity = 1f; view.Layer.ShadowOffset = CGSize.Empty; view.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("view", view); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"H:|-{(FieldFrame.X + (FieldFrame.Width - (size.Width + PaddingInErrorPopUp*2))).ToString(CultureInfo.InvariantCulture)}-[view({(size.Width + PaddingInErrorPopUp*2) .ToString(CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"V:|-{(imgframe.Y + imgframe.Height).ToString(CultureInfo.InvariantCulture)}-[view({(size.Height + PaddingInErrorPopUp*2).ToString( CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); var lbl = new UILabel(CGRect.Empty) { Font = font, Lines = 0, BackgroundColor = UIColor.Clear, Text = Message, TextColor = FontColor }; view.AddSubview(lbl); lbl.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("lbl", lbl); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"H:|-{PaddingInErrorPopUp.ToString(CultureInfo.InvariantCulture)}-[lbl({size.Width.ToString(CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"V:|-{PaddingInErrorPopUp.ToString(CultureInfo.InvariantCulture)}-[lbl({size.Height.ToString(CultureInfo.InvariantCulture)})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); }
public void Show(ToastType type) { var image = this.theSettings().images[type]; var font = UIFont.SystemFontOfSize(this.theSettings().fontSize); var str = new NSAttributedString(this.text, font); var textSize = str.GetBoundingRect(new CGSize(260, 50), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; textSize.Width = textSize.Width + 5; var label = new UILabel(new CGRect(0, 0, textSize.Width + this.LeftAndRightPadding, textSize.Height + this.TopAndBottomPadding)) { BackgroundColor = UIColor.Clear, TextColor = UIColor.White, TextAlignment = UITextAlignment.Left, Text = this.text, Lines = 0, Font = UIFont.SystemFontOfSize(this.theSettings().fontSize) }; if (this.theSettings().useShadow) { label.ShadowColor = UIColor.DarkGray; label.ShadowOffset = new CGSize(1, 1); } var button = new UIButton(UIButtonType.Custom); if (image != null) { button.Frame = this.ToastFrameForImageSize(image.Size, textSize); /*switch (this.theSettings().imageLocation) * { * case ToastImageLocation.Left:*/ label.TextAlignment = UITextAlignment.Left; label.Center = new CGPoint(image.Size.Width + (this.LeftAndRightPadding * 2) + (((button.Frame.Size.Width - image.Size.Width) - (this.LeftAndRightPadding * 2)) / 2), button.Frame.Size.Height / 2); /* break; * * case ToastImageLocation.Top: * label.TextAlignment = UITextAlignment.Center; * label.Center = new CGPoint(button.Frame.Size.Width / 2, (image.Size.Height + (this.TopAndBottomPadding * 2)) + (((button.Frame.Size.Height - image.Size.Height) - (this.TopAndBottomPadding * 2)) / 2)); * break; * }*/ } else { button.Frame = new CGRect(0, 0, textSize.Width + (this.LeftAndRightPadding * 2), textSize.Height + (this.TopAndBottomPadding * 2)); label.Center = new CGPoint(button.Frame.Size.Width / 2, button.Frame.Size.Height / 2); } var rect8 = label.Frame; rect8.X = (nfloat)Math.Ceiling((double)rect8.X); rect8.Y = (nfloat)Math.Ceiling((double)rect8.Y); label.Frame = rect8; button.AddSubview(label); if (image != null) { var view = new UIImageView(image); view.Frame = this.FrameForImage(type, button.Frame); button.AddSubview(view); } button.BackgroundColor = UIColor.FromRGBA(this.theSettings().bgRed, this.theSettings().bgGreen, this.theSettings().bgBlue, this.theSettings().bgAlpha); button.Layer.CornerRadius = this.theSettings().cornerRadius; var window = UIApplication.SharedApplication.Windows[0]; var empty = CGPoint.Empty; var orientation = UIApplication.SharedApplication.StatusBarOrientation; switch (this.theSettings().gravity) { case ToastGravity.Top: empty = new CGPoint(window.Frame.Size.Width / 2, 0x2d); break; case ToastGravity.Bottom: empty = new CGPoint(window.Frame.Size.Width / 2, window.Frame.Size.Height - 0x2d); break; case ToastGravity.Center: empty = new CGPoint(window.Frame.Size.Width / 2, window.Frame.Size.Height / 2); break; } empty = new CGPoint(empty.X + this.theSettings().offsetLeft, empty.Y + this.theSettings().offsetTop); button.Center = empty; button.Frame = RectangleFExtensions.Integral(button.Frame); var timer = NSTimer.CreateTimer(TimeSpan.FromSeconds(this.theSettings().duration / 1000), t => this.HideToast()); NSRunLoop.Main.AddTimer(timer, 0); button.Tag = (nint)CURRENT_TOAST_TAG; var view2 = window.ViewWithTag((nint)CURRENT_TOAST_TAG); if (view2 != null) { view2.RemoveFromSuperview(); } button.Alpha = 0; window.AddSubview(button); UIView.BeginAnimations(null, IntPtr.Zero); button.Alpha = 1; UIView.CommitAnimations(); this.view = button; button.AddTarget(new EventHandler(this.HideToastEventHandler), UIControlEvent.TouchDown); ToastSetting.SharedSettings = null; }
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); } }
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); } }
public override void Draw(RectangleF rect) { float[] color = Color.CGColor.Components; UIGraphics.BeginImageContext(new SizeF(30, 20)); CGContext ctx = UIGraphics.GetCurrentContext(); ctx.SetRGBFillColor(color[0], color[1], color[2], 1); ctx.SetShadowWithColor(SizeF.Empty, 7f, UIColor.Black.CGColor); ctx.AddLines(new[] { new PointF(15, 5), new PointF(25, 25), new PointF(5, 25) }); ctx.ClosePath(); ctx.FillPath(); UIImage viewImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); var imgframe = new RectangleF((ShowOnRect.X + ((ShowOnRect.Width - 30) / 2)), ((ShowOnRect.Height / 2) + ShowOnRect.Y), 30, 13); var img = new UIImageView(viewImage); AddSubview(img); img.TranslatesAutoresizingMaskIntoConstraints = false; var dict = new NSDictionary("img", img); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat(string.Format(@"H:|-{0}-[img({1})]", imgframe.X, imgframe.Width), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat(string.Format(@"V:|-{0}-[img({1})]", imgframe.Y, imgframe.Height), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); UIFont font = UIFont.FromName(FontName, FontSize); var message = new NSAttributedString(Message, font); SizeF size = message.GetBoundingRect(new SizeF(FieldFrame.Width - (PaddingInErrorPopUp) * 2, 1000), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; size = new SizeF((float)Math.Ceiling(size.Width), (float)Math.Ceiling(size.Height)); var view = new UIView(RectangleF.Empty); InsertSubviewBelow(view, img); view.BackgroundColor = Color; view.Layer.CornerRadius = 5f; view.Layer.ShadowColor = UIColor.Black.CGColor; view.Layer.ShadowRadius = 5f; view.Layer.Opacity = 1f; view.Layer.ShadowOffset = SizeF.Empty; view.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("view", view); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( string.Format(@"H:|-{0}-[view({1})]", FieldFrame.X + (FieldFrame.Width - (size.Width + (PaddingInErrorPopUp * 2))), size.Width + (PaddingInErrorPopUp * 2)), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( string.Format(@"V:|-{0}-[view({1})]", imgframe.Y + imgframe.Height, size.Height + (PaddingInErrorPopUp * 2)), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); var lbl = new UILabel(RectangleF.Empty) { Font = font, Lines = 0, BackgroundColor = UIColor.Clear, Text = Message, TextColor = FontColor }; view.AddSubview(lbl); lbl.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("lbl", lbl); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( string.Format(@"H:|-{0}-[lbl({1})]", PaddingInErrorPopUp, size.Width), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( string.Format(@"V:|-{0}-[lbl({1})]", PaddingInErrorPopUp, size.Height), NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); }
public static CGRect BoundingRectWithSize(this NSAttributedString attrString, CGSize size, NSStringDrawingOptions options) => attrString.GetBoundingRect(size, options, null);
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 UIFont font = null; var ext = System.IO.Path.GetExtension(textDef.FontName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { try { textDef.FontName = LoadFontFile(textDef.FontName); font = UIFont.FromName(textDef.FontName, textDef.FontSize); } catch (Exception exc) { CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName); } } else { // font font = UIFont.FromName(textDef.FontName, textDef.FontSize); //NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize); } if (font == null) { font = UIFont.FromName("Arial", textDef.FontSize); CCLog.Log("{0} not found. Defaulting to Arial.", textDef.FontName); } // color var foregroundColor = UIColor.White; // alignment var horizontalAlignment = textDef.Alignment; var verticleAlignement = textDef.LineAlignment; var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? UITextAlignment.Right : (CCTextAlignment.Center == horizontalAlignment) ? UITextAlignment.Center : UITextAlignment.Left; // LineBreak var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? UILineBreakMode.CharacterWrap : (CCLabelLineBreak.Word == textDef.LineBreak) ? UILineBreakMode.WordWrap : UILineBreakMode.Clip; var nsparagraphStyle = (NSMutableParagraphStyle)NSParagraphStyle.Default.MutableCopy(); nsparagraphStyle.LineBreakMode = lineBreak; nsparagraphStyle.Alignment = textAlign; // Create a new attributed string definition var nsAttributes = new UIStringAttributes(); // 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 CGSize(textDef.Dimensions.Width, textDef.Dimensions.Height); var layoutAvailable = true; if (dimensions.Width <= 0) { dimensions.Width = 8388608; layoutAvailable = false; } if (dimensions.Height <= 0) { dimensions.Height = 8388608; layoutAvailable = false; } var boundingRect = stringWithAttributes.GetBoundingRect(new CGSize((int)dimensions.Width, (int)dimensions.Height), NSStringDrawingOptions.UsesLineFragmentOrigin, null); if (!layoutAvailable) { if (dimensions.Width == 8388608) { dimensions.Width = boundingRect.Width; } if (dimensions.Height == 8388608) { dimensions.Height = boundingRect.Height; } } imageWidth = (int)dimensions.Width; imageHeight = (int)dimensions.Height; // Alignment var xOffset = (nfloat)0.0f; switch (textAlign) { case UITextAlignment.Left: xOffset = 0; break; case UITextAlignment.Center: xOffset = (dimensions.Width - boundingRect.Width) / 2.0f; break; case UITextAlignment.Right: xOffset = dimensions.Width - boundingRect.Width; break; default: break; } // Line alignment var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement || boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to bottom : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0 // align to top : (imageHeight - boundingRect.Height) / 2.0f; // align to center //Find the rect that the string will draw into inside the dimensions var drawRect = new CGRect(xOffset , yOffset , boundingRect.Width , boundingRect.Height); UIImage image = null; CGContext context = null; try { UIGraphics.BeginImageContext(new CGSize(imageWidth, imageHeight)); context = UIGraphics.GetCurrentContext(); //Set antialias or not context.SetShouldAntialias(textDef.isShouldAntialias); stringWithAttributes.DrawString(drawRect); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); // 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 (context != null) { context.Dispose(); context = null; } if (stringWithAttributes != null) { stringWithAttributes.Dispose(); stringWithAttributes = null; } } return(new CCTexture2D()); }
// TODO using Core Text here is going to be a huge problem because we have to // change the coordinate system for every call to DrawString rather than changing // it once for all the calls. Not even sure we have enough info (the height of // the coord system or UIView) to do the transform? // TODO if we know the text is one-line, we can skip the big transform and just use // the textmatrix thing. public void DrawString(string s, float box_x, float box_y, float box_width, float box_height, Xamarin.Forms.LineBreakMode lineBreak, Xamarin.Forms.TextAlignment horizontal_align, Xamarin.Forms.TextAlignment vertical_align ) { _c.SaveState(); // TODO _c.SetTextDrawingMode (CGTextDrawingMode.Fill); // Core Text uses a different coordinate system. _c.TranslateCTM(0, _overall_height); _c.ScaleCTM(1, -1); var attributedString = new NSAttributedString(s, _ct_attr); float text_width; float text_height; if ( (horizontal_align != TextAlignment.Start) || (vertical_align != TextAlignment.Start)) { // not all of the alignments need the bounding rect. don't // calculate it if not needed. var sizeAttr = attributedString.GetBoundingRect( new SizeF( (float)box_width, int.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null ); text_width = sizeAttr.Width; //text_height = sizeAttr.Height; //text_height = sizeAttr.Height + uif.Descender; // descender is negative text_height = _font_ui.CapHeight; } else { text_width = 0; text_height = 0; } //Console.WriteLine ("width: {0} height: {1}", text_width, text_height); float x; switch (horizontal_align) { case Xamarin.Forms.TextAlignment.End: x = (box_x + box_width) - text_width; break; case Xamarin.Forms.TextAlignment.Center: x = box_x + (box_width - text_width) / 2; break; case Xamarin.Forms.TextAlignment.Start: default: x = box_x; break; } float y; switch (vertical_align) { case Xamarin.Forms.TextAlignment.End: y = box_y + text_height; break; case Xamarin.Forms.TextAlignment.Center: y = (box_y + box_height) - (box_height - text_height) / 2; break; case Xamarin.Forms.TextAlignment.Start: default: y = (box_y + box_height); break; } _c.TextPosition = new PointF((float)x, (float)(_overall_height - y)); // I think that by using CTLine() below, we are preventing multi-line text. :-( using (var textLine = new CTLine(attributedString)) { textLine.Draw(_c); } //gctx.StrokeRect (new RectangleF(x, height - y, text_width, text_height)); _c.RestoreState(); }
public override void Draw(CGRect rect) { nfloat[] color = Color.CGColor.Components; UIGraphics.BeginImageContext(new CGSize(30, 20)); CGContext ctx = UIGraphics.GetCurrentContext(); ctx.SetFillColor(color[0], color[1], color[2], 1); ctx.SetShadow(CGSize.Empty, 7f, UIColor.Black.CGColor); ctx.AddLines(new[] { new CGPoint(15, 5), new CGPoint(25, 25), new CGPoint(5, 25) }); ctx.ClosePath(); ctx.FillPath(); UIImage viewImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); var imgframe = new CGRect(ShowOnRect.X + (ShowOnRect.Width - 30) / 2, ShowOnRect.Height / 2 + ShowOnRect.Y, 30, 13); var img = new UIImageView(viewImage); AddSubview(img); img.TranslatesAutoresizingMaskIntoConstraints = false; var dict = new NSDictionary("img", img); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat($@"H:|-{imgframe.X}-[img({imgframe.Width})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); img.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat($@"V:|-{imgframe.Y}-[img({imgframe.Height})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); UIFont font = UIFont.FromName(FontName, FontSize); var message = new NSAttributedString(Message, font); var size = message.GetBoundingRect(new CGSize(FieldFrame.Width - PaddingInErrorPopUp * 2, 1000), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size; size = new CGSize((nfloat)Math.Ceiling(size.Width), (nfloat)Math.Ceiling(size.Height)); var view = new UIView(CGRect.Empty); InsertSubviewBelow(view, img); view.BackgroundColor = Color; view.Layer.CornerRadius = 5f; view.Layer.ShadowColor = UIColor.Black.CGColor; view.Layer.ShadowRadius = 5f; view.Layer.Opacity = 1f; view.Layer.ShadowOffset = CGSize.Empty; view.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("view", view); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"H:|-{FieldFrame.X + (FieldFrame.Width - (size.Width + PaddingInErrorPopUp*2))}-[view({size.Width + PaddingInErrorPopUp*2})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); view.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"V:|-{imgframe.Y + imgframe.Height}-[view({size.Height + PaddingInErrorPopUp*2})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); var lbl = new UILabel(CGRect.Empty) { Font = font, Lines = 0, BackgroundColor = UIColor.Clear, Text = Message, TextColor = FontColor }; view.AddSubview(lbl); lbl.TranslatesAutoresizingMaskIntoConstraints = false; dict = new NSDictionary("lbl", lbl); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"H:|-{PaddingInErrorPopUp}-[lbl({size.Width})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); lbl.Superview.AddConstraints( NSLayoutConstraint.FromVisualFormat( $@"V:|-{PaddingInErrorPopUp}-[lbl({size.Height})]", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, dict)); }