{"id":3021,"date":"2010-04-12T16:17:41","date_gmt":"2010-04-12T14:17:41","guid":{"rendered":"http:\/\/www.devapp.it\/wordpress\/?p=3021"},"modified":"2010-04-12T19:16:08","modified_gmt":"2010-04-12T17:16:08","slug":"t031-usiamo-font-true-type-nelle-nostre-applicazioni-iphone-ttf","status":"publish","type":"post","link":"https:\/\/www.devapp.it\/wordpress\/t031-usiamo-font-true-type-nelle-nostre-applicazioni-iphone-ttf\/","title":{"rendered":"T#031 &#8211; Usiamo Font True Type personali nelle nostre applicazioni iPhone (ttf)"},"content":{"rendered":"<p><a href=\"http:\/\/www.devapp.it\/wordpress\/wp-content\/uploads\/2010\/04\/TRUE-TYPE-icona.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.devapp.it\/wordpress\/wp-content\/uploads\/2010\/04\/TRUE-TYPE-icona.jpg\" alt=\"Icona True-Type\" title=\"TRUE-TYPE-icona\" width=\"66\" height=\"85\" class=\"alignleft size-full wp-image-3033\" \/><\/a>Salve a tutti, per chi non mi conoscesse (un po&#8217; tutti credo :P) sono l&#8217;autore di &#8220;<a href=\"http:\/\/itunes.apple.com\/it\/app\/punti-patente\/id366266298?mt=8&amp;affId=403275\" target=\"_blank\">Punti Patente Plus<\/a>&#8221; rilasciata venerd\u00ec 9 aprile sull&#8217;AppStore e attualmente al primo posto tra le applicazioni pi\u00f9 acquistate! Oggi vi parler\u00f2 di un argomento che pu\u00f2 sembrare banale, ma, per quanto mi riguarda, mi ha richiesto non poche notti insonni.<br \/>\nCome sapete, \u00e8 gi\u00e0 possibile usare un <strong>Font True Type<\/strong> all&#8217;interno di iPhone, semplicemente specificando il suo <em>FontFamily<\/em>.<!--more--><\/p>\n<p>Esempio:<\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\nUILabel *hello_label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,30)];\r\n[hello_label setFont:[UIFont fontWithName:@\"Arial\" size:30]];\r\n<\/pre>\n<p>Naturalmente se volete usare dei font non precaricati su iPhone, o addirittura avere la possibilit\u00e1 di scaricarli da internet ed utilizzarli nell&#8217;applicativo onfly, questo codice non va bene, in quanto, dovreste prima registrarli.<\/p>\n<p>Ecco una soluzione (non proprio indolore):<\/p>\n<p><strong>File:<\/strong> <em>CustomFontBase.h<\/em><\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\n@interface CustomFontBase : UIView {\r\nNSMutableString *curText;\r\nUIColor *fontColor;\r\nUIColor *bgColor;\r\nint fontSize;\r\nNSString *fontName;\r\nNSString *fontExtension;\r\nfloat autoSizeWidth;\r\nint glyphOffset;\r\nBOOL isGlowing;\r\nUIColor *glowColor;\r\n}\r\n\r\n- (void)updateText:(NSString*)newText;\r\n- (void)initTextWithSize:(float)size color:(UIColor*)color bgColor:(UIColor*)bgColor;\r\n- (void)setGlow:(BOOL)glowing withColor:(UIColor*)color;\r\n- (void)autoSizeWidthNow;\r\n\r\n@property (nonatomic, retain) NSMutableString *curText;\r\n\r\n@end\r\n<\/pre>\n<p><strong>File:<\/strong> <em>CustomFontBase.m<\/em><\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\n#import \"CustomFontBase.h\"\r\n\r\n@implementation CustomFontBase\r\n\r\n@synthesize curText;\r\n\r\n- (id)initWithFrame:(CGRect)frame {\r\nif (self = [super initWithFrame:frame]) {\r\n\/\/ set defaults\r\n[self setBackgroundColor:[UIColor clearColor]];\r\nbgColor = [UIColor clearColor];\r\n[self setCurText: [[NSMutableString alloc] initWithString:@\"\"] ];\r\nfontColor = [UIColor whiteColor];\r\nfontSize = 15;\r\nisGlowing = FALSE;\r\n[self setContentMode:UIViewContentModeTopLeft];  \/\/ make sure it doesn't scale\/deform when setFrame is called\r\n}\r\nreturn self;\r\n}\r\n\r\n- (void)drawRect:(CGRect)rect {\r\n\/\/ get context and flip for normal coordinates\r\nCGContextRef context =  UIGraphicsGetCurrentContext();\r\nCGContextTranslateCTM ( context, 0, self.bounds.size.height );\r\nCGContextScaleCTM ( context, 1.0, -1.0 );\r\n\r\n\/\/ Get the path to our custom font and create a data provider.\r\nNSString *fontPath = [[NSBundle mainBundle] pathForResource:fontName ofType:fontExtension];\r\nCGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);\r\n\/\/ Create the font with the data provider, then release the data provider.\r\nCGFontRef customFont = CGFontCreateWithDataProvider(fontDataProvider);\r\nCGDataProviderRelease(fontDataProvider);\r\n\/\/ Set the customFont to be the font used to draw.\r\nCGContextSetFont(context, customFont);\r\n\r\n\/\/ prepare characters for printing\r\nNSString *theText = [NSString stringWithString: curText];\r\nint length = [theText length];\r\nunichar chars[length];\r\nCGGlyph glyphs[length];\r\n[theText getCharacters:chars range:NSMakeRange(0, length)];\r\n\r\n\/\/ draw bg\r\nif( bgColor != [UIColor clearColor] )\r\n{\r\nCGRect bgRect = CGRectMake (0, 0, self.bounds.size.width, self.bounds.size.height);\r\nCGContextSetFillColorWithColor( context, bgColor.CGColor );\r\nCGContextFillRect( context, bgRect );\r\n}\r\n\r\n\/\/ Set how the context draws the font, what color, how big.\r\nCGContextSetTextDrawingMode(context, kCGTextFill);\r\nCGContextSetFillColorWithColor(context, fontColor.CGColor );\r\nCGContextSetFontSize(context, fontSize);\r\n\r\n\/\/ set a glow?\r\nif( isGlowing ) {\r\n\/\/CGContextSetShadow(context, CGSizeMake(0,0), 3 );\r\nCGContextSetShadowWithColor( context, CGSizeMake(0,0), 3, glowColor.CGColor );\r\n}\r\n\r\n\/\/ Loop through the entire length of the text.\r\nfor (int i = 0; i &lt; length; ++i) {\r\n\/\/ Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.\r\nglyphs[i] = [theText characterAtIndex:i] + glyphOffset;\r\n}\r\n\r\n\/\/ draw the glyphs\r\nCGContextShowGlyphsAtPoint( context, 0, 0 + fontSize * .25, glyphs, length ); \/\/ hack the y-point to make sure it&#039;s not cut off below font baseline - this creates a perfect vertical fit\r\n\r\n\/\/ get width of text for autosizing the frame later (perhaps)\r\nCGPoint textEnd = CGContextGetTextPosition( context );\r\nautoSizeWidth = textEnd.x;\r\n\r\n\/\/ clean up the font\r\nCGFontRelease( customFont );\r\n}\r\n\r\n\/\/ call this after creating the LandscapeText object to set the styling\r\n- (void)initTextWithSize:(float)size color:(UIColor*)color bgColor:(UIColor*)txtBgColor {\r\n\/\/ store font properties\r\nfontColor = color;\r\nfontSize = size;\r\nbgColor = txtBgColor;\r\n\r\n\/\/ autoscale height to font size\r\n[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, fontSize)];\r\n}\r\n\r\n\/\/ set new text to display\r\n- (void)updateText:(NSString*)newText {\r\n[self setCurText: [NSString stringWithString:newText] ];\r\n[self setNeedsDisplay];\r\n}\r\n\r\n- (void)setGlow:(BOOL)glowing withColor:(UIColor*)color {\r\nglowColor = color;\r\nisGlowing = glowing;\r\n}\r\n\r\n- (void)autoSizeWidthNow {\r\n\/\/printf( &quot;autoSizeWidth = %f \\n&quot;, autoSizeWidth );\r\n[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, autoSizeWidth, fontSize)];\r\n}\r\n\r\n- (void)dealloc {\r\n[curText release];\r\n[super dealloc];\r\n}\r\n\r\n@end\r\n<\/pre>\n<p>Questa classe definisce una <em>UIView<\/em> con tutte le properties necessarie a gestire un font:<\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\nNSMutableString *curText;   \/\/testo da visualizzare\r\nUIColor *fontColor;                 \/\/colore del testo\r\nUIColor *bgColor;                    \/\/colore dello sfondo\r\nint fontSize;                                 \/\/grandezza del font\r\nNSString *fontName;              \/\/nome del font\r\nNSString *fontExtension;    \/\/estensione : nel nostro caso sar\u00e0 sempre ttf (true type font)\r\nfloat autoSizeWidth;              \/\/se vogliamo che il testo si adatti alla lunghezza dello spazio disponibile\r\nint glyphOffset;                       \/\/questa e le successive tre properties ci interessano per l'effetto glowing  \r\nBOOL isGlowing;\r\nUIColor *glowColor;         \r\n<\/pre>\n<p>Questa classe cos\u00ec definita ci servir\u00e0 per usare un <strong>font true type<\/strong>, ma non deve essere usata direttamente, la estenderemo per ogni font nuovo che vorremo utilizzare.<\/p>\n<p><strong>File:<\/strong>  <em>CustomFontBase.h<\/em><\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\n#import \"CustomFontBase.h\"\r\n\r\n@interface CustomFontMyFont : CustomFontBase {\r\n\r\n}\r\n\r\n@end\r\n<\/pre>\n<p><strong>File:<\/strong> <em>CustomFontMyFont.m<\/em><\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\n#import \"CustomFontMyFont.h\"\r\n\r\n@implementation CustomFontMyFont\r\n\r\n- (id)initWithFrame:(CGRect)frame {\r\nif (self = [super initWithFrame:frame]) {\r\n\/\/ Initialization code\r\nfontName = @\"NomeDelMioFontParticolare\";\r\nfontExtension = @\"ttf\";\r\nglyphOffset = -29;       \r\n}\r\nreturn self;\r\n}\r\n\r\n- (void)dealloc {\r\n[super dealloc];\r\n}\r\n\r\n@end\r\n<\/pre>\n<p>L&#8217;idea \u00e8 quella di avere una classe per ogni custom font che ci serve.<\/p>\n<p>E ora vediamo l&#8217;utilizzo:<\/p>\n<p><strong>File:<\/strong> <em>Test.m<\/em><\/p>\n<pre lang=\"objc\" escaped=\"true\">\r\n#import \"CustomFontMyFont.h\"\r\n\r\n........\r\n\r\nCustomFontMyFont *myLabel = [[[CustomFontMyFont alloc] initWithFrame:CGRectMake(10, 50, 320, 200)] autorelease];\r\n[myLabel initTextWithSize:[slider value]  color:[UIColor whiteColor] bgColor:[UIColor clearColor] ];\r\n[myLabel setGlow:YES withColor:[UIColor yellowColor]];\r\n[myLabel updateText:@\"http:\/\/www.sviluppoiphoneitalia.com\"];\r\n<\/pre>\n<p>Spero sia tutto chiaro, se aveste dubbi o domande, lasciate un commento o, ancora meglio, utilizzate il nostro forum \ud83d\ude09<\/p>\n<p>Alla prossima..<\/p>\n<p>..e mi raccomando.. date il vostro contributo acquistando la mia applicazione \ud83d\ude09<\/p>\n<p><a href=\"http:\/\/itunes.apple.com\/it\/app\/punti-patente\/id366266298?mt=8&amp;affId=403275\" target=\"_blank\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.devapp.it\/wordpress\/wp-content\/uploads\/2010\/04\/bn-Punti-Patente-Plus.jpg\" alt=\"Banner Punti Patente Plus\" title=\"bn-Punti-Patente-Plus\" width=\"470\" height=\"61\" class=\"aligncenter size-full wp-image-3029\" srcset=\"https:\/\/www.devapp.it\/wordpress\/wp-content\/uploads\/2010\/04\/bn-Punti-Patente-Plus.jpg 470w, https:\/\/www.devapp.it\/wordpress\/wp-content\/uploads\/2010\/04\/bn-Punti-Patente-Plus-300x38.jpg 300w\" sizes=\"auto, (max-width: 470px) 100vw, 470px\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Salve a tutti, per chi non mi conoscesse (un po&#8217; tutti credo :P) sono l&#8217;autore di &#8220;Punti&#8230;<\/p>\n","protected":false},"author":169,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[176,175,23],"class_list":["post-3021","post","type-post","status-publish","format-standard","hentry","category-tutorial-pratici","tag-font-personalizzati","tag-font-true-type","tag-xcode"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/posts\/3021","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/users\/169"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/comments?post=3021"}],"version-history":[{"count":13,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/posts\/3021\/revisions"}],"predecessor-version":[{"id":3049,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/posts\/3021\/revisions\/3049"}],"wp:attachment":[{"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/media?parent=3021"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/categories?post=3021"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devapp.it\/wordpress\/wp-json\/wp\/v2\/tags?post=3021"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}