刚接触ios,看到富文本特效,想做一个demo,根据富文本内容,生成一张图片,并保存到本地,结果字符背景色死活不生效,下面是本人的测试代码,请高手们解救本人这个菜鸟
-(UIImage*)creatImage3 : (int)width andHeight:(int) height andTextContent:(NSAttributedString*)content { UIColor *backgroundColor = [UIColor greenColor]; //字符背景色,就是这个没有生效 UIColor *foregroundColor = [UIColor redColor]; //文字前景色,这个生效了 NSDictionary *attrsDic = @{NSForegroundColorAttributeName: foregroundColor, NSBackgroundColorAttributeName: backgroundColor }; NSAttributedString *attributedString_str_atts = [[NSAttributedString alloc] initWithString:@"http://www.baidu.com" attributes:attrsDic]; UIGraphicsBeginImageContextWithOptions( CGSizeMake(width, height), NO, 1); //获取bitmap上下文 CGContextRef context = UIGraphicsGetCurrentContext(); //旋转一下方向,否则绘制出来的图片是上下颠倒的 CGContextConcatCTM(context, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, height), 1.0, -1.0)); //文本绘制区域 CGRect textRect = CGRectMake(1, 1, width - 2, height - 2); //自定义绘制NSAttributedString CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString_str_atts); CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, textRect); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); CFRelease(path); CFRelease(framesetter); CTFrameDraw(frame, context); CFRelease(frame); //获取生成的图片 UIImage *image=UIGraphicsGetImageFromCurrentImageContext(); //释放上下文 CGContextRelease(context); //保存绘制好的图片到文件中 //先将图片转换为二进制数据,然后再将图片写到文件中 UIImagePNGRepresentation(image); NSData *data=UIImagePNGRepresentation(image); NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); NSString* thepath = [paths lastObject]; thepath = [thepath stringByAppendingPathComponent:@"abc.png"]; thepath=@"/Users/liumingjie/abc.png"; NSFileManager *fileManager = [NSFileManager defaultManager]; if ( ![fileManager fileExistsAtPath:thepath]) { [fileManager createFileAtPath:thepath contents:nil attributes:nil]; } [data writeToFile:thepath atomically:YES]; return image; }
解决方案
50
刚刚找了了一个文章,解释了原因:
正常情况下一个NSxxx属性,对于一个kCTxxx属性,例如NSForegroundColorAttributeName对应CoreText里面的kCTForegroundColorAttributeName;而NSBackgroundColorAttributeName没有对应的kCTBackgroundColorAttributeName属性,所以CoreText不支持背景色;
参考链接:
http://stackoverflow.com/questions/6707906/nsbackgroundcolorattributename-like-attribute-in-nsattributedstring-on-ios
正常情况下一个NSxxx属性,对于一个kCTxxx属性,例如NSForegroundColorAttributeName对应CoreText里面的kCTForegroundColorAttributeName;而NSBackgroundColorAttributeName没有对应的kCTBackgroundColorAttributeName属性,所以CoreText不支持背景色;
参考链接:
http://stackoverflow.com/questions/6707906/nsbackgroundcolorattributename-like-attribute-in-nsattributedstring-on-ios