效果:
image.png
image.png
//实现文字在上,点9图背景的AttributedString
//image = 背景图片
//text = 上面文字
//font = 文字字体
//color = 文字颜色
//space = 背景和文字的间距,背景要比文字大才好看
- (void)getImageTextWithParams:(NSDictionary *)params callBack:(void (^)(NSMutableAttributedString *imageAtbs))callBack
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
UIImage *image = params[@"image"];
image = [UIImage imageWithCGImage:image.CGImage scale:2 orientation:image.imageOrientation];
image = [image stretchableImageWithLeftCapWidth:image.size.width * 0.5 topCapHeight:0];
NSString *text = params[@"text"];
CGFloat imageToTextSpace = [params[@"space"] floatValue];
CGFloat containerHegiht = [params[@"height"] floatValue];
UIFont *textFont = params[@"font"];
UIColor *textColor = params[@"color"];
NSDictionary *textAttributedDict = @{
NSFontAttributeName: textFont,
NSForegroundColorAttributeName: textColor
};
CGSize textSize = [text sizeWithAttributes:textAttributedDict];
CGSize imageSize = CGSizeMake(textSize.width + imageToTextSpace * 2, MIN(containerHegiht, textFont.lineHeight + 4));
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawPath(context, kCGPathStroke);
[text drawInRect:CGRectMake(imageToTextSpace, (containerHegiht - textFont.lineHeight) * 0.5, textSize.width, textFont.lineHeight) withAttributes:textAttributedDict];
UIImage *contentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSMutableAttributedString *imageAtbs = [NSMutableAttributedString yy_attachmentStringWithContent:contentImage contentMode:UIViewContentModeCenter attachmentSize:imageSize alignToFont:textFont alignment:YYTextVerticalAlignmentCenter];
dispatch_async(dispatch_get_main_queue(), ^{
if (callBack) {
callBack(imageAtbs);
}
});
});
}
网友评论