iOS_YYLabel實(shí)現(xiàn)多標(biāo)簽,文字+背景功能

效果:


image.png

image.png
//實(shí)現(xiàn)文字在上,點(diǎn)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);
            }
        });
    });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容