どこでも検索しましたが、解決策が見つかりませんでした。画像 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;
}