ios - "Inverse"来自 NSAttributedString 的 UIImage

标签 ios uiimage nsattributedstring uigraphicscontext

我从 NSAttributedString 创建了一个 UIImage:

UIFont *font = [UIFont systemFontOfSize:12.0f];
NSDictionary *attributes = @{NSFontAttributeName:font,
                             NSForegroundColorAttributeName:[UIColor greenColor]};

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:title attributes:attributes];

// Create the image here
UIImage *image = [self imageFromAttributedString:attributedString];


#pragma mark - Get image from attributed string

- (UIImage *)imageFromAttributedString:(NSAttributedString *)text
{
    UIGraphicsBeginImageContextWithOptions(text.size, NO, 0.0);

    // draw in context
    [text drawAtPoint:CGPointMake(0.0, 0.0)];

    // transfer image
    UIImage *image = [UIGraphicsGetImageFromCurrentImageContext() imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIGraphicsEndImageContext();

    return image;
}

我的问题是,创建具有相同文本但“反转”的图像的最佳方式是什么,即 [UIColor greenColor] 和白色字体文本?

最佳答案

使用NSBackgroundColorAttributeName将背景设置为绿色,NSForegroundColorAttributeName将文本设置为白色。

文档包括:

NSString *const NSForegroundColorAttributeName;
NSString *const NSBackgroundColorAttributeName;

位于https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/Reference/Reference.html#//apple_ref/doc/uid/TP40011688

关于ios - "Inverse"来自 NSAttributedString 的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23620902/

相关文章:

ios - 将 NSLocalizedString 转换为 NSAttributedString 大写文本

objective-c - NSTimer、NSBlockOperation NSInvocation 还是 NSOperation?

cocoa-touch - 使用 UIImage 从 URL 异步加载图像时出现明显延迟

iOS MapKit 通过道路连接 map 上的多个点

ios - Swift iOS 为 UIImage 添加不可见边框

swift 2 : UICollectionView - is it possible to return cell asynchronously?

objective-c - 如何使用核心文本和属性字符串伪造上标和下标?

ios - 如何在 iOS 7 的 UITextView 中设置属性文本的颜色和对齐方式?

iphone - 如何随时间将 NSString 转换为 NSDate?

ios - UIButton 突出显示的背景图像未显示