iphone - 如何为可拉伸(stretch)的 UIImage 着色

标签 iphone ios objective-c ipad uikit

我想为可拉伸(stretch)的 UIImage 着色,但无法使其工作。 在这篇文章的帮助下:How to change the color of an UIImage我已成功为 UIImage 着色,但当我使其可拉伸(stretch)时,颜色未设置在"new"框架上。

以下是我如何使用类别设置颜色:

+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color
{
    UIImage *image = [UIImage imageNamed:name];
    if (color == nil)
        return image;
    CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, rect, image.CGImage);
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [UIImage imageWithCGImage:img.CGImage
                               scale:1.0
                         orientation:UIImageOrientationDownMirrored];
}

如有任何建议,我们将不胜感激...

最佳答案

这段代码应该可以工作:

+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)theColor
{
    UIImage *baseImage = [UIImage imageNamed:name];
    UIGraphicsBeginImageContext(baseImage.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSaveGState(ctx);
    CGContextClipToMask(ctx, area, baseImage.CGImage);
    [theColor set];
    CGContextFillRect(ctx, area);
    CGContextRestoreGState(ctx);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextDrawImage(ctx, area, baseImage.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

关于iphone - 如何为可拉伸(stretch)的 UIImage 着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999067/

相关文章:

iphone - 响应UIWebView点击 Action 调用原生代码页

iphone - UISegmentedControl 值以编程方式更改

ios - 模拟器可以运行项目,但设备不能这样做

ios - GCDAsyncSocket 委托(delegate)调用不起作用

ios - iOS中从服务器获取数据

ios - NSXMLParser "foundCharacters"未调用委托(delegate)方法

iphone - 在 ios 中使用自动释放池的限制

iphone - 有没有非私有(private) API 替代方案?

ios - 如何在 Swift 中从 JSON 数组中删除项目(使用 SwiftyJSON)

iphone - 追加字符串时的内存管理?