我想用alpha着色图像,并创建了以下课程。如果您发现任何问题,请告诉我。
我已经将类命名为CSTintedImageView
并且它继承自UIView
因为UIImageView
不调用drawRect:
方法,如先前的答复中所述。我已经设置了一个指定的初始化程序,该初始化程序类似于在UIImageView
类中找到的初始化程序。
用法:
CSTintedImageView * imageView = [[CSTintedImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
imageView.tintColor = [UIColor redColor];
CSTintedImageView.h
@interface CSTintedImageView : UIView
@property (strong, nonatomic) UIImage * image;
@property (strong, nonatomic) UIColor * tintColor;
- (id)initWithImage:(UIImage *)image;
@end
CSTintedImageView.m
#import "CSTintedImageView.h"
@implementation CSTintedImageView
@synthesize image=_image;
@synthesize tintColor=_tintColor;
- (id)initWithImage:(UIImage *)image
{
self = [super initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
if(self)
{
self.image = image;
//set the view to opaque
self.opaque = NO;
}
return self;
}
- (void)setTintColor:(UIColor *)color
{
_tintColor = color;
//update every time the tint color is set
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
//resolve CG/iOS coordinate mismatch
CGContextScaleCTM(context, 1, -1);
CGContextTranslateCTM(context, 0, -rect.size.height);
//set the clipping area to the image
CGContextClipToMask(context, rect, _image.CGImage);
//set the fill color
CGContextSetFillColor(context, CGColorGetComponents(_tintColor.CGColor));
CGContextFillRect(context, rect);
//blend mode overlay
CGContextSetBlendMode(context, kCGBlendModeOverlay);
//draw the image
CGContextDrawImage(context, rect, _image.CGImage);
}
@end
0
我想为图像添加色彩参考。结果应该看起来像Photoshop中的“乘法”混合模式,其中白色将替换为“ 色调” :
我将不断更改颜色值。
后续:我会将代码执行此操作,并将其放入ImageView的drawRect:方法中,对吗?
像往常一样,与链接相反, 代码片段将极大地帮助我理解。
更新:用建议的代码Ramin子类化UIImageView。
我把它放在我的视图控制器的viewDidLoad:中:
我看到了图像,但是没有着色。我还尝试加载其他图像,在IB中设置图像,然后在视图控制器中调用setNeedsDisplay:。
更新 :未调用drawRect :。
最终更新:我发现一个旧项目已正确设置了imageView,因此我可以测试Ramin的代码,并且它的工作原理很吸引人!
最终,最终更新:
对于那些刚刚了解Core Graphics的人来说,这是可能可行的最简单的方法。
在子类化的UIView中: