我想写一个UIView子类,除其他外,为它下面的某种颜色着色。这是我想出,但遗憾的是似乎并没有正常工作:如何使子视图在iPhone上的一部分屏幕上色调?
#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”中的函数(这让我非常头疼终于实现),这似乎工作正常。任何人都知道我在做什么错了?是否有可能做到这一点,或者我应该以不同的方式接近它?
您可以使用CALayer获取此行为,检查了这一点http://stackoverflow.com/a/18805190/2567532 – lekksi 2013-09-14 18:52:36