简体   繁体   中英

iPhone - cleaning the context of a UIView outside drawRect

I have this UIView that I subclassed and implemented my own drawRect method.

When the drawRect method runs the first time, I grab the context in a variable using

ctx = UIGraphicsGetCurrentContext();

later on the code, outside drawRect, I am trying to clean the whole context filling it with a transparent color, then I do:

CGContextClearRect(ctx, self.bounds);
[self setNeedsDisplay];

The problem is that the context is not erased and continues as before.

At this point ctx is not nil.

am I missing something?

thanks

Is it not possible to move the clearing into drawRect? I'm not sure if drawing out side of drawRect is possible, and even if it is, it's not exactly how it's intended to work.

How about this?

[[UIColor clear] set];  ///< set clear color for stroke & fill
CGContextFillRect(ctx, self.bounds);

And, the ctx from CGContextGetCurrentContext() is only valid in the drawRect:, or between UIGraphicesPushContext() and UIGraphicsPopContext(), or UIGraphcisBeginImageContext() and UIGraphicsEndImageContext().

This way works faster then CGContextFillRect:

-(void) drawRect:(CGRect)rect{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);
}

您提供的代码不是很多,但是您是否尝试保留上下文?

CGContextRetain(ctx)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM