NSStringåã®æååãç»åã«å¤æãã¾ãããサイズを指定して空のUIImageオブジェクトを生成する - iOSアプリ開発の逆引き辞典ãããã¼ã¹ã¨ãã¦ãã¾ãã
- (UIImage *)imageWithString:(NSString *)text { // æç»ãããµã¤ãº CGSize size = CGSizeMake(34, 18); // ããããããå½¢å¼ã®ã°ã©ãã£ãã¯ã¹ã³ã³ããã¹ãã®çæ // 第2å¼æ°ã®opaqueã`NO`ã«ãããã¨ã§èæ¯ãéæã«ãªã UIGraphicsBeginImageContextWithOptions(size, NO, 0); // æç»ããæååã®æ å ±ãæå®ãã //-------------------------------------- // æåæç»æã«åæ ãããå½±ã®æå® NSShadow *shadow = [[NSShadow alloc] init]; shadow.shadowOffset = CGSizeMake(0.f, -0.5f); shadow.shadowColor = [UIColor darkGrayColor]; shadow.shadowBlurRadius = 0.f; // æåæç»ã«ä½¿ç¨ãããã©ã³ãã®æå® UIFont *font = [UIFont boldSystemFontOfSize:14.0f]; // ãã©ã°ã©ãé¢é£ã®æ å ±ã®æå® NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init]; style.alignment = NSTextAlignmentCenter; style.lineBreakMode = NSLineBreakByClipping; NSDictionary *attributes = @{ NSFontAttributeName: font, NSParagraphStyleAttributeName: style, NSShadowAttributeName: shadow, NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor clearColor] }; // æååãæç»ãã [text drawInRect:CGRectMake(0, 0, size.width, size.height) withAttributes:attributes]; // ç¾å¨ã®ã°ã©ãã£ãã¯ã¹ã³ã³ããã¹ãã®ç»åãåå¾ãã UIImage *image = nil; image = UIGraphicsGetImageFromCurrentImageContext(); // ç¾å¨ã®ã°ã©ãã£ãã¯ã¹ã³ã³ããã¹ãã¸ã®ç·¨éãçµäº // (ã¹ã¿ãã¯ã®å é ããåé¤ãã) UIGraphicsEndImageContext(); return image; }
使ãæ¹ã
NSString *text = @"ï¼»ã»ï¼½ "; UIImage *image = [self imageWithString:text];