Skip to content

Instantly share code, notes, and snippets.

@blitzvb
Last active April 17, 2021 02:01
Show Gist options
  • Save blitzvb/7582002 to your computer and use it in GitHub Desktop.
Save blitzvb/7582002 to your computer and use it in GitHub Desktop.
here how to create a UIImage from a font. #xamarin #ios
public static UIImage ImageWithFont(string fontName,float fontSize,SizeF imageSize,UIColor color,string text)
{
if (fontName != null && text != null && color != null) {
UIGraphics.BeginImageContextWithOptions (imageSize, false, 0.0f);
NSAttributedString attrString = new NSAttributedString (text, new UIStringAttributes () {
Font = UIFont.FromName (fontName,fontSize),
ForegroundColor = color
});
NSStringDrawingContext strContext = new NSStringDrawingContext ();
RectangleF rectFont = attrString.GetBoundingRect (imageSize,NSStringDrawingOptions.UsesDeviceMetrics, strContext);
attrString.DrawString (new RectangleF (imageSize.Width/2 - rectFont.Width/2,imageSize.Height/2 - rectFont.Height/2,imageSize.Width,imageSize.Height));
UIImage image = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();
return image;
}
return null;
}
@GnanaPriyaNamasivayam
Copy link

Your workaround works perfectly when we parse the string to UIImage. In my case, am using the UNICODE string, when I use it in the place of text - I get the exact Unicode string but not the expected icon of that UNICODE.

Do you have any idea of this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment