我想编写一个 UIView 子类,除其他外,将其下方的任何内容着色为某种颜色。这是我想出的,但不幸的是它似乎无法正常工作:
#import <UIKit/UIKit.h>
@class MyOtherView;
@interface MyView : UIView
{
MyOtherView *subview;
}
@end
@implementation MyView
- (id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
frame.origin.x += 100.0;
frame.origin.y += 100.0;
frame.size.width = frame.size.height = 200.0;
subview = [[MyOtherView alloc] initWithFrame:frame];
[self addSubview:subview];
[subview release];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Draw a background to test out on
UIImage *image = [UIImage imageNamed:@"somepic.png"];
[image drawAtPoint:rect.origin];
const CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blueColor] setFill];
rect.size.width = rect.size.height = 200.0;
CGContextFillRect(ctx, rect);
}
@end
@interface MyOtherView : UIView
@end
@implementation MyOtherView
- (void)drawRect:(CGRect)rect
{
// This should tint "MyView" but it doesn't.
const CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeScreen);
[[UIColor redColor] setFill];
CGContextFillRect(ctx, rect);
CGContextRestoreGState(ctx);
}
@end
我希望“MyOtherView”在它重叠的地方将“MyView”涂成红色,但它只是在上面绘制一个不透明的红色块。但是,如果我从“MyOtherView”复制 -drawRect: 函数并将其附加到“MyView”中的函数,这似乎可以正常工作(这让我很头疼最终意识到)。有人知道我在做什么错吗?甚至有可能做到这一点,还是我应该以不同的方式接近它?