开发一个需求,需要实现这种效果
image.png
其中直播标签我用了UILabel画出来,并想将其作为一个字符加入到整个title中去排版,但后来才发现属性字符串是不支持加入UIView进行排版的,只可以加UIImage,所以就想办法把UILabel转为UIImage。
UILabel转UIImage的代码如下:
因为下面注释掉的代码会导致标签模糊,后改用上边的代码解决了问题。
- (UIImage*)imageWithUIView:(UIView*) view
{
UIGraphicsBeginImageContextWithOptions(view.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
// 下面这段代码会模糊。
// UIGraphicsBeginImageContext(view.bounds.size);
// CGContextRef ctx = UIGraphicsGetCurrentContext();
// [view.layer renderInContext:ctx];
// UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return tImage;
}
属性字符串:
UIImage *img = [self imageWithUIView:self.liveTag];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:title];
// 图片:置顶
NSTextAttachment *stickAttach = [[NSTextAttachment alloc] init];
stickAttach.image = img;
CGFloat lineHeight = self.titleLabel.font.lineHeight;
CGFloat descender = self.titleLabel.font.descender;
CGFloat realWidth = 30.0f;
CGFloat realHeight = 18.0f;
stickAttach.bounds = CGRectMake(0, descender + (lineHeight - realHeight) / 2, realWidth, realHeight);
NSAttributedString *attachmentAttrStr = [NSAttributedString attributedStringWithAttachment:stickAttach];
[attrStr insertAttributedString:attachmentAttrStr atIndex:0];
// 图片与文字的间距
[attrStr insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
self.titleLabel.attributedText = attrStr;
网友评论