Last active
April 17, 2021 02:01
-
-
Save blitzvb/7582002 to your computer and use it in GitHub Desktop.
here how to create a UIImage from a font. #xamarin #ios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?