2012-05-10 35 views
5

我设法通过添加以下视图顶部得到的灰阶一个UIView:UIView灰度。图中不被重绘

@interface GreyscaleAllView : UIView 

@property (nonatomic, retain) UIView *underlyingView; 

@end 

@implementation GreyscaleAllView 

@synthesize underlyingView; 

- (void)drawRect:(CGRect)rect { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // draw the image 
    [self.underlyingView.layer renderInContext:context]; 

    // set the blend mode and draw rectangle on top of image 
    CGContextSetBlendMode(context, kCGBlendModeColor); 
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0); 
    CGContextFillRect(context, rect); 
    [super drawRect:rect]; 
} 

@end 

它的工作原理,但内容没有更新,除非我手动调用setNeedsDisplay。 (我可以按一个UIButton并且动作会触发,但外观没有任何变化)因此,为了表现得像预期的那样,我每秒调用setNeedsDisplay 60次。我究竟做错了什么?

UPDATE:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    GreyscaleAllView *grey = [[[GreyscaleAllView alloc] initWithFrame:self.view.frame] autorelease]; 
    grey.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 
    grey.userInteractionEnabled = NO;  
    [self.view addSubview:grey]; 
} 

我已经完成了这些垫层意见重绘:

inits与此OverlayView的的视图 - 控制

@implementation GreyscaleAllView 

- (void)setup { 

    self.userInteractionEnabled = FALSE; 
    self.contentMode = UIViewContentModeRedraw; 

    [self redrawAfter:1.0/60.0 repeat:YES]; 

} 

- (void)redrawAfter:(NSTimeInterval)time repeat:(BOOL)repeat { 

    if(repeat) { 
     // NOTE: retains self - should use a proxy when finished 
     [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(setNeedsDisplay) userInfo:nil repeats:YES]; 
    } 

    [self setNeedsDisplay]; 
} 
+0

做同样可以您是从初始化此灰度视图的位置添加代码? – rishi

+0

添加视图控制器初始化代码并重绘代码 – jalmaas

+0

尝试使用GreyscaleAllView * grey = [[[GreyscaleAllView alloc] initWithFrame:CGRectMake(0,0,320,480)] autorelease]; – rishi

回答

1

你真正想要的是什么仅当父视图重绘时才让子视图重绘,在这种情况下,您可以覆盖父v中的-setNeedsDisplay并在GreyscaleAllView上拨打-setNeedsDisplay。这需要继承UIView的UIViewControllerview属性。在控制器

即实现loadView,并设置

self.view = [[CustomView alloc] initWithFrame:frame]; 

如上所述,其中CustomView覆盖setNeedsDisplay

@implementation CustomView 

- (void)setNeedsDisplay 
{ 
    [grayView setNeedsDisplay]; // grayView is a pointer to your GreyscaleAllView 
    [super setNeedsDisplay]; 
} 

@end 

为了完整起见,你也应该为-setNeedsDisplayInRect: