图片加文字

- (NSDictionary *)addText:(NSString *)someText toImage:(NSDictionary *)attachment {

NSDictionary *dictValue = [EntrysOperateHelper dictFromJsonString:attachment[@"value"]];

CGFloat w = [dictValue[@"width"] floatValue];

CGFloat h =  [dictValue[@"height"] floatValue];

NSString *filePath = [CoredataManager filePathWithKey:dictValue[@"fileKey"] andOption:nil];

UIImage * img = [UIImage imageWithContentsOfFile:filePath];

int fontSize = (MIN(w, h) * 0.0468);

CGSize stringSize = [someText moaSizeWithFont:[UIFont systemFontOfSize:fontSize]];

//上下文的大小

//    CGColorSpaceRef colorSpace =CGColorSpaceCreateDeviceRGB(); //创建颜色

//    //创建上下文

//    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

//

//    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);//将img绘至context上下文中

//

//    char * text= (char *)[someText cStringUsingEncoding:NSASCIIStringEncoding];

//

//    CGContextSelectFont(context, "Arial", fontSize, kCGEncodingMacRoman);//设置字体的大小

//    CGContextSetTextDrawingMode(context, kCGTextFill);//设置字体绘制方式

//

////    文字的颜色

//    CGContextSetFillColorWithColor(context, [[UIColor colorWithHexString:@"#ffffff" alpha:0.9] CGColor]);

////    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);

//    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

//

//    //文字的位置

//    CGContextShowTextAtPoint(context, 10, 10, text, strlen(text));

//

//    CGImageRef imgCombined = CGBitmapContextCreateImage(context);//创建CGImage

//    CGContextRelease(context);

//    CGColorSpaceRelease(colorSpace);

//    UIImage *retImage = [UIImage imageWithCGImage:imgCombined]; //获得添加水印后的图片

//    CGImageRelease(imgCombined);

CGSize size= CGSizeMake(w, h); // 画布大小

UIGraphicsBeginImageContextWithOptions (size, NO, 0.0);

[img drawAtPoint:CGPointMake (0, 0)];

// 获得一个位图图形上下文

CGContextRef context= UIGraphicsGetCurrentContext();

CGContextDrawPath(context, kCGPathStroke);

[someText drawAtPoint:CGPointMake(w - fontSize - stringSize.width, h - fontSize - stringSize.height) withAttributes:@{

NSFontAttributeName:[UIFont systemFontOfSize:fontSize],

NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#ffffff" alpha:0.9],

NSStrokeWidthAttributeName:@(-3),

NSStrokeColorAttributeName:[UIColor colorWithHexString:@"#000000" alpha:0.5]}];

// 返回绘制的新图形

UIImage * retImage= UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

NSData *data = UIImageJPEGRepresentation(retImage, 1.0);

NSDictionary * dict = [IMMessageCell genertateDictWithContent:data andType:IMContentTypePicture option:nil];

[self removeFileAtDraft:[EntrysOperateHelper objFromString:attachment[@"value"]][@"fileKey"]];

NSAssert([dict isKindOfClass:[NSDictionary class]], @"genrerate IM attachment path error");

return dict;

}

你可能感兴趣的:(图片加文字)