ios开发之属性字符串NSAttributeString与NSString相互转换包含图片

分享几个常用的 属性字符串NSAtrributeString 和 NSString 普通字符串的 转换方法:

一:把普通的字符串,替换为包含图片的属性字符串

plist 文件,图片 格式见下图:

+(NSMutableAttributedString *)stringToAttributeString:(NSString *)text
{
    //先把普通的字符串text转化生成Attributed类型的字符串
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];

    NSString * zhengze = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]"; //正则表达式 ,例如  [呵呵] 这种形式的通配符

    NSError * error;
<span style="font-family: Arial, Helvetica, sans-serif;"> NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];//正则表达式</span>
    if (!re)
    {
        NSLog(@"%@",[error localizedDescription]);//打印错误
    }

    NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];//遍历字符串,获得所有的匹配字符串

    NSBundle *bundle = [NSBundle mainBundle];
    NSString * path = [bundle pathForResource:@"emotions" ofType:@"plist"];  //plist文件,制作一个 数组,包含文字,表情图片名称
    NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];  //获取 所有的数组

    //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
    for (int j =(int) arr.count - 1; j >= 0; j--) {
        //NSTextCheckingResult里面包含range
        NSTextCheckingResult * result = arr[j];

        for (int i = 0; i < face.count; i++) {
            if ([[text substringWithRange:result.range] isEqualToString:face[i][@"chs"]])//从数组中的字典中取元素
            {
                NSString * imageName = [NSString stringWithString:face[i][@"png"]];

                NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];//添加附件,图片

                textAttachment.image = [UIImage imageNamed:imageName];

                NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

                [attStr replaceCharactersInRange:result.range withAttributedString:imageStr];//替换未图片附件

                break;
            }
        }
    }
    return attStr;
}

二:获取属性字符串的size大小:

注:对包含文字和图片的属性字符串,需要根据实际情况,调节其大小

+(CGSize)getAttributedTextSize:(NSString *)text
{
    //先把普通的字符串text转化生成Attributed类型的字符串
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];

    NSString * zhengze = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";

    NSError * error;

    NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
    if (!re)
    {
        NSLog(@"正则表达式匹配错误%@",[error localizedDescription]);
    }

    NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];

    if (!arr.count)//说明字符串中没有表情通配符,是普通的文本,则计算文本size
    {
        NSDictionary *[email protected]{NSFontAttributeName: [UIFont systemFontOfSize:14]};

        CGSize size1=[text boundingRectWithSize:CGSizeMake(160, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;

        if (size1.height<=60)
        {
            size1.height=60;
        }

        else
        {
            size1.height+=15;
        }

        return size1;
    }

    NSBundle *bundle = [NSBundle mainBundle];
    NSString * path = [bundle pathForResource:@"emotions" ofType:@"plist"];
    NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

    //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
    for (int j =(int) arr.count - 1; j >= 0; j--) {
        //NSTextCheckingResult里面包含range
        NSTextCheckingResult * result = arr[j];

        for (int i = 0; i < face.count; i++) {
            if ([[text substringWithRange:result.range] isEqualToString:face[i][@"chs"]])
            {
                NSString * imageName = [NSString stringWithString:face[i][@"png"]];

                NSTextAttachment * textAttachment = [[NSTextAttachment alloc]init];

                textAttachment.image = [UIImage imageNamed:imageName];

                NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];

                [attStr replaceCharactersInRange:result.range withAttributedString:imageStr];

                break;
            }
        }
    }

    CGSize size2=[attStr boundingRectWithSize:CGSizeMake(180, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;

    size2.height+=40;  //表情文字增加高度

    return size2;//返回属性字符串的尺寸
}

三: 属性字符串转为普通字符串, 关键点: 图片的二进制比对(可以放入到一个 子线程去做)

图片二进制比对,获得图片名称:

//不能直接得到串的名字?
-(NSString *)stringFromImage:(UIImage *)image
{
    NSArray *face=[self getAllImagePaths];

    NSData * imageD = UIImagePNGRepresentation(image);

    NSString * imageName;

    for (int i=0; i<face.count; i++)
    {
        UIImage *image=[UIImage imageNamed:face[i][@"png"]];
        NSData *data=UIImagePNGRepresentation(image);
        if ([imageD isEqualToData:data])
        {
            imageName=face[i][@"chs"];
            //NSLog(@"匹配成功!");
        }
    }

    return imageName;
}

-(NSArray *)getAllImagePaths//数组结构还是上述的截图的数组结构
{
    NSBundle *bundle = [NSBundle mainBundle];

    NSString * path = [bundle pathForResource:@"emotions" ofType:@"plist"];

    NSArray * face = [[NSArray alloc]initWithContentsOfFile:path];

    return face;
}

属性字符串转换为普通字符串:

假设为TextView,label,button同理

//把带有图片的属性字符串转成普通的字符串
-(NSString *)textString
{
    NSAttributedString * att = self.attributedText;

    NSMutableAttributedString * resutlAtt = [[NSMutableAttributedString alloc]initWithAttributedString:att];

    __weak __block UITextView * copy_self = self;
    //枚举出所有的附件字符串
    [att enumerateAttributesInRange:NSMakeRange(0, att.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        //key-NSAttachment
        //NSTextAttachment value类型
        NSTextAttachment * textAtt = attrs[@"NSAttachment"];//从字典中取得那一个图片
        if (textAtt)
        {
            UIImage * image = textAtt.image;
            NSString * text = [copy_self stringFromImage:image];
            [resutlAtt replaceCharactersInRange:range withString:text];

        }

    }];

    return resutlAtt.string;

}

原文地址:http://blog.csdn.net/yangbingbinga/

时间: 2024-08-03 09:45:59

ios开发之属性字符串NSAttributeString与NSString相互转换包含图片的相关文章

iOS开发-检测用户截屏, 并获取所截图片

微信可以检测到用户截屏行为(Home + Power),并在稍后点击附加功能按钮时询问用户是否要发送刚才截屏的图片,这个用户体验非常好.于是乎, 我也想着实现这个功能. 在iOS7之前, 如果用户截屏,系统会自动取消屏幕上的所有 touch 事件,(使用 touchesCancelled:withEvent: 这个方法)那么我们就可以检测这个方法的调用,然后加载本地最新图片再加以判断来实现我们的目的.但在 iOS 7 之后,截屏不再会取消屏幕的 touch 事件,所以导致了 Snapchat 和

ios 开发中获取字符串中重复的字符的rang

iOS 开发中经常会遇到处理字符串的问题,对于一个字符串经常会遇见里面包含重复的字符需要对重复的字符进行处理,下面的代码就是对重复字符进行处理的操作,具体代码如下所示: /** * 返回重复字符的location * * @param text 初始化的字符串 * @param findText 查找的字符 * * @return 返回重复字符的location */ - (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSStr

IOS开发之本地化--字符串表的生产

IOS开发时,本地化需要使用字符串表,mac提供了自动生成工具-genstrings.可以使用genstrings从.m文件生成字符串表. 1.在mac设备上打开终端应用程序. 2.导航到代码目录.实现这一点的最简单的方法是在终端窗口输入cd空格,然后从finder打开程序文件夹,拖拽到终端窗口,一个长路径名就会出现,回车即可.可以通过ls命令查看目录内容确认. 3.通过以下代码生产字符串表: genstrings -o Base.lproj *m -o:指明输出的文件夹 *.m:告诉genst

ios开发transform属性

#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageV; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, t

iOS开发之 判断字符串的第一个字符是否是中文或者字母开头

     NSString *titleStr = @"琳小兮";  //先截取字符串,拿到第一个字符         NSString *firstStr = [titleStr substringToIndex:1];                  //判断是不是中文开头的         BOOL isFirst = [self isZhongWenFirst:firstStr];         if (isFirst != 0) {            NSLog(@&

iOS开发-automaticallyAdjustsScrollViewInsets属性

最近遇到一个问题是这样的,App一般自己都会有一个UINavigationController,顶部TableView如果有tableHeaderView如果设置起始位置是(0,0)是在导航栏的下面的,为了更好地UI希望从屏幕的(0,0)开始,就遇到了上面的这个问题,简单的看一下效果: 主要代码如下: - (UITableView *)tableView { if (!_tableView) { _tableView = [[UITableView alloc] initWithFrame:CG

iOS开发Item属性总结

一.UINavigationItem1> 获得方式self.navigationItem // self是指控制器 2> 作用可以用来设置当前控制器顶部导航栏的内容// 设置导航栏中间的内容self.navigationItem.titleself.navigationItem.titleView 二.UIBarButtonItem1> 用在什么地方// 设置导航栏左上角的内容self.navigationItem.leftBarButtonItem// 设置导航栏右上角的内容self.

IOS 开发中判断字符串是否为空字符的方法

- (BOOL) isBlankString:(NSString *)string { if (string == nil || string == NULL) { return YES; } if ([string isKindOfClass:[NSNull class]]) { return YES; } if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]=

iOS开发——使用技术OC篇&amp;保存(获取)图片到(自定义)相册

保存(获取)图片到(自定义)相册 最近在学 iOS相关技术(绘图篇实现画板功能)的时候设计到了两个常用的知识点,那就是保存图片到相册和葱相册中获取图片. 只是个人比较好奇拓展一些技术,说的难听点叫做装牛角尖,好听点就是为了装逼而已,所以在保存相册的时候使用真及测试发现不能保存到我iPhone里 main的自定义相册里面,就查看文档和资料,也借鉴别人的分享实现了想要的功能,就把他给记录下来,这个虽然没有直接保存和获取常用但是也是一项很好的实用技术. 一:首先来看看怎么获取相册的图片: 1 // 弹