我想寫一個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