Google+ Followers

2013年12月11日 星期三

iOS 開發筆記 - 使用 Core Graphics 進行文字繪圖輸出並設定 NSString Attributes (Font、Alignment) 等

draw string

整理一年多前的程式碼,發現用的函數已經在 iOS 7 宣告為 deprecated 啦,恰好重看 CS193P 時,得知 NSAttributedString 這東西,以為是最新出來的,沒想到這在 iOS 3.2 就存在啦。

順便把一些筆記都記下吧:

+ (UIImage *)buildImageAndDrawText:(NSString *)text size:(CGSize)size ios7:(BOOL)iOS7SDK
{
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1, 1, 1, 1);
    CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height));

    UIFont *font = [UIFont italicSystemFontOfSize:15];
    UIColor *fontColor = [UIColor blueColor];

    if (iOS7SDK) {
        NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
        [paragrapStyle setLineBreakMode:NSLineBreakByWordWrapping];
        [paragrapStyle setAlignment:NSTextAlignmentCenter];
     
        [text drawInRect:CGRectIntegral(CGRectMake(0, size.height/2, size.width, size.height))
          withAttributes:@{
                           NSParagraphStyleAttributeName: paragrapStyle,
                           NSFontAttributeName: font,
                           NSForegroundColorAttributeName: fontColor}
         ];
    } else {
        [fontColor set];
        [text drawInRect:CGRectIntegral(CGRectMake(0, size.height/2, size.width, size.height)) withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
    }
 
    UIImage *outImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outImage;
}


用法:

self.imageView = [YourClass buildImageAndDrawText:@"iOS app development @ blog.changyy.org" size:CGSizeMake(300, 300) ios7:YES];

細節可參考 Core Graphics Framework Reference


沒有留言:

張貼留言