Mac開發-NSAttributedString顏色模糊問題記錄

問題描述

使用富文本顯示時,出現模糊的問題
問題如下:
在這裏插入圖片描述
我這裏只需要3個字特殊顏色:
在這裏插入圖片描述
代碼如下:

	NSString *colorStr = @"\"上講臺\"";
    NSString *originStr = @"爲了方便老師上課前檢查音視頻質量,點擊\"上講臺\"僅打開老師的攝像頭和麥克風";
    NSMutableAttributedString *mutaStr = [[NSMutableAttributedString alloc] initWithString:originStr attributes:[NSDictionary dictionaryWithObjects:@[[NSColor whiteColor]] forKeys:@[NSForegroundColorAttributeName]]];
    [mutaStr setAttributes:[NSDictionary dictionaryWithObjects:@[[NSColor colorWithRed:62/255.f green:175/255.f blue:14/255.f alpha:1]] forKeys:@[NSForegroundColorAttributeName]] range:[originStr rangeOfString:colorStr]];
    [mutaStr addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"FZY4JW--GB1-0" size:13]
                      range:NSMakeRange(0, originStr.length)];

解決方案

解決方案是: 設置文本的NSBackgroundColorAttributeName與背景色一致

	NSString *colorStr = @"\"上講臺\"";
    NSString *originStr = @"爲了方便老師上課前檢查音視頻質量,點擊\"上講臺\"僅打開老師的攝像頭和麥克風";
    NSMutableAttributedString *mutaStr = [[NSMutableAttributedString alloc] initWithString:originStr attributes:[NSDictionary dictionaryWithObjects:@[[NSColor whiteColor]] forKeys:@[NSForegroundColorAttributeName]]];
    [mutaStr setAttributes:[NSDictionary dictionaryWithObjects:@[[NSColor colorWithRed:62/255.f green:175/255.f blue:14/255.f alpha:1]] forKeys:@[NSForegroundColorAttributeName]] range:[originStr rangeOfString:colorStr]];
    [mutaStr addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"FZY4JW--GB1-0" size:13]
                      range:NSMakeRange(0, originStr.length)];
    //添加NSBackgroundColorAttributeName
    [mutaStr addAttribute:NSBackgroundColorAttributeName value:[NSColor colorWithRed:46/255.0 green:53/255.0 blue:59/255.0 alpha:1]
                    range:NSMakeRange(0, originStr.length)];

最終效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章