我到处搜索,但没有找到解决方案。我有图像 1。如何以编程方式为它们着色以获取图像 2 和 3?以下是这些图片:
我通过 Photoshop 应用到它们的色调是简单的 2 色线性渐变。
我的问题是:我怎样才能以编程方式实现这种效果?
解决方案: jrtc27 给了我几乎可行的例子。我修复了它(对于 ARC)并使其可重用(使用 UIImage 的类别)。就这个:
- (UIImage *)tintedWithLinearGradientColors:(NSArray *)colorsArr {
CGFloat scale = self.scale;
UIGraphicsBeginImageContext(CGSizeMake(self.size.width * scale, self.size.height * scale));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, self.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGRect rect = CGRectMake(0, 0, self.size.width * scale, self.size.height * scale);
CGContextDrawImage(context, rect, self.CGImage);
// Create gradient
UIColor *colorOne = [colorsArr objectAtIndex:1]; // top color
UIColor *colorTwo = [colorsArr objectAtIndex:0]; // bottom color
NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, (id)colorTwo.CGColor, nil];
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(space, (__bridge CFArrayRef)colors, NULL);
// Apply gradient
CGContextClipToMask(context, rect, self.CGImage);
CGContextDrawLinearGradient(context, gradient, CGPointMake(0,0), CGPointMake(0,self.size.height * scale), 0);
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return gradientImage;
}