ios之字符串生成图片

- (void)viewDidLoad

{

    [superviewDidLoad];

    

    NSString *aa = @"        aaaaaaaaaa\r\n"

    "             bbbbbbbbbbb\r\n"

    "          ccccccccccccc 12345\r\n"

    "\r\n"

    "Date: MM/DD/YYYY         Time:HH:MM PM\r\n"

    "--------------------------------------\r\n"

    "eeee\r\n"

    "ffffff            ggggggggn       Total\r\n"

    "hhhhh      iiiiiiiiiii     11.11\n"

    "ggggg      kkkkkkkkkk       22.22\n"

    "lllll      mmmmmmmmmm        33.33\n"

   ;

    

    

    int width = 576;

    

    NSString *fontName = @"Courier";

    

    double fontSize = 35.0;

    

    //  fontSize *= multiple;

    fontSize *= 2;

    

    UIFont *font = [UIFont fontWithName:fontName size:fontSize];

    

    CGSize size = CGSizeMake(width, 10000);

    CGSize messuredSize = [aa sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];

 

if ([[UIScreenmainScreen] respondsToSelector:@selector(scale)]) {

if ([[UIScreenmainScreen] scale] == 2.0) {

UIGraphicsBeginImageContextWithOptions(messuredSize, NO, 1.0);

}

        else {

UIGraphicsBeginImageContext(messuredSize);

}

}

    else {

UIGraphicsBeginImageContext(messuredSize);

}

    

    CGContextRef ctr = UIGraphicsGetCurrentContext();

    UIColor *color = [UIColorwhiteColor];

    [color set];

    

    CGRect rect = CGRectMake(0, 0, messuredSize.width + 1, messuredSize.height + 1);

    CGContextFillRect(ctr, rect);

    

    color = [UIColorblackColor];

    [color set];

    

    [aa drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap];

    UIImage *imageToPrint = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    

    

    NSData *imageData = UIImagePNGRepresentation(imageToPrint);

    NSArray *documents1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    // 设置保存文件名称

    NSString *path1 = [documents1[0] stringByAppendingPathComponent:kImageFileName];

    // 保存文件

      NSLog(@"%@", path1);

     NSLog(@"沙盒的路径为:%@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);

    [imageData writeToFile:path1 atomically:YES];

}

posted on 2014-04-16 22:10  林源  阅读(462)  评论(0编辑  收藏  举报

导航