iphone - 如何给图像着色/显示颜色?

标签 iphone objective-c xcode

我想做的两件事,它们是相关的:

  1. 展示任何颜色的方 block 。这样我就可以随时将颜色更改为其他颜色。
  2. 将 UIImage 着色为不同的颜色。降低 alpha 值的颜色叠加层在这里可以发挥作用,但假设这是一张具有透明背景的图像,并且没有占据图像的整个正方形。

有什么想法吗?

最佳答案

另一种选择是像这样在 UIImage 上使用类别方法...

// Tint the image, default to half transparency if given an opaque colour.
- (UIImage *)imageWithTint:(UIColor *)tintColor {
    CGFloat white, alpha;
    [tintColor getWhite:&white alpha:&alpha];
    return [self imageWithTint:tintColor alpha:(alpha == 1.0 ? 0.5f : alpha)];
}

// Tint the image
- (UIImage *)imageWithTint:(UIColor *)tintColor alpha:(CGFloat)alpha {

    // Begin drawing
    CGRect aRect = CGRectMake(0.f, 0.f, self.size.width, self.size.height);
    UIGraphicsBeginImageContext(aRect.size);

    // Get the graphic context
    CGContextRef c = UIGraphicsGetCurrentContext(); 

    // Converting a UIImage to a CGImage flips the image, 
    // so apply a upside-down translation
    CGContextTranslateCTM(c, 0, self.size.height); 
    CGContextScaleCTM(c, 1.0, -1.0);

    // Draw the image
    [self drawInRect:aRect];

    // Set the fill color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextSetFillColorSpace(c, colorSpace);

    // Set the mask to only tint non-transparent pixels
    CGContextClipToMask(c, aRect, self.CGImage);

    // Set the fill color
    CGContextSetFillColorWithColor(c, [tintColor colorWithAlphaComponent:alpha].CGColor);

    UIRectFillUsingBlendMode(aRect, kCGBlendModeColor);

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    // Release memory
    CGColorSpaceRelease(colorSpace);

    return img;
}

关于iphone - 如何给图像着色/显示颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5145953/

相关文章:

iphone - OpenCV 检测 iphone 方向

jquery - 应用对数动画

xcode - 没有这样的模块 "CreateMLUI"

iphone - 如何使 UISegmentedControl 的选定部分变暗?

ios - 无法获取 iphone 构建版本

ios - NSNonLossyASCIIStringEncoding 返回 nil

ios - 如何对包含 NSIndexPath 整数数组的 NSMutableArray 进行排序?

swift - UITableViewCell内容滚动后消失

xcode - 在 Xcode 中,如何进入 lambda 函数?

iphone - 使用 iPhone SDK 控制、查找和连接 wifi 热点?