iOS_bookmark

图文混排 -之- 图片垂直对齐(垂直居中)

2017-06-18  本文已影响814人  wustzhy
需求:
managerPic.png
开发思路
实现 法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];

关键之处
//在输入框中,表情和文字在水平方向上并不是对齐状态,上下有差值 
//解决方法:微调
let height = textView.font.lineHeight    
attachment.bounds = CGRectMake(0, -4, height, height)   
上一篇下一篇

猜你喜欢

热点阅读