需求:
-
昵称(文字)+身份(渐变背景色+文字)
UI设计师给的效果图
开发思路
- 法1 - 昵称label + 身份label
实现难度低, 内心有木有一丝不屑呢哈哈... 换个对得起自己的方式吧, 图文混排呗~ - 法2 - ①文字nickName <--> append <--> ②图片managerPic
实现 法2
1 - 身份图片生成 - 图片上绘文字(水印)
image.png
// 贴代码
// 图文 合成
+ (UIImage *)imageWithText:(NSString *)text
textFont:(UIFont *)font
textColor:(UIColor *)textColor
textFrame:(CGRect)textFrame
originImage:(UIImage *)image
imageLocationViewFrame:(CGRect)viewFrame {
if (!text) { return image; }
if (!textColor) { textColor = [UIColor blackColor]; }
if (!image) { return nil; }
if (viewFrame.size.height==0 || viewFrame.size.width==0 || textFrame.size.width==0 || textFrame.size.height==0 )
{ return nil; }
// 用UIGraphics进行2D图像渲染 不要用UIGraphicsBeginImageContext(size); 不然图片会模糊
UIGraphicsBeginImageContextWithOptions(viewFrame.size, NO, 0.0);
[image drawInRect:viewFrame];
CGContextRef context= UIGraphicsGetCurrentContext();
CGContextDrawPath (context, kCGPathStroke );
NSDictionary *attr = @{NSFontAttributeName: font, NSForegroundColorAttributeName : textColor };
//位置显示
[text drawInRect:textFrame withAttributes:attr];
UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return aimg;
}
2 - 文字 拼接 图片
image.png
// 文字__昵称
NSMutableAttributedString * mutAttStr_nickName = [[NSMutableAttributedString alloc]initWithString:[message.senderDisplayName stringByAppendingString:@" "]]; // 空格 隔开
[mutAttStr_nickName addAttribute:NSFontAttributeName
value:(14)
range:NSMakeRange(0, message.senderDisplayName.length)];
// 图片(图片+水印 合成图)
UIImage * image = [ZHFGroupChatViewController imageWithText:@"吧主"
textFont:(20)
textColor:[UIColor whiteColor]
textFrame:CGRectMake((8), (0), (40), (28))
originImage:UIIMAGE(@"managerPic")
imageLocationViewFrame:CGRectMake((0), (0), (56), (28))
];
// attachment
NSTextAttachment *textAttach_image = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
// 调节 图文混排中, 图的垂直对齐 - 调整y值
textAttach_image.bounds = CGRectMake(0, -2, image.size.width/2, image.size.height/2);
textAttach_image.image = image ;
NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttach_image];
// 拼接
[mutAttStr_nickName appendAttributedString:textAttachmentString];
关键之处
- 拼接后,发现效果是 图片底部 与 label底部平齐, 显然不是想要的结果, 于是乎, google "ios, 图文混排中 Attachment 的 图片, 怎么靠中对齐",终于找到一处正解👉点击跳转
//在输入框中,表情和文字在水平方向上并不是对齐状态,上下有差值
//解决方法:微调
let height = textView.font.lineHeight
attachment.bounds = CGRectMake(0, -4, height, height)
网友评论