我如何在drawrect之外做直接类型的东西?

And*_*rew 7 iphone graphics core-graphics objective-c ios

我有一个名为Icon的基于UIView的类.在那里,我希望有类似这样的代码:

UIView *finalView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
finalView.backgroundColor = [UIColor redColor];

UIGraphicsBeginImageContext(finalView.bounds.size);
[finalView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

问题是,我不想把它放在drawRect中,因为当我的应用程序在另一个视图中创建每个Icon时调用它.我如何将这种代码放在我的Icon类中的其他地方?我试过把它放在一个地方,它给了我:

CGContextSaveGState: invalid context 0x0
CGContextSetAlpha: invalid context 0x0
CGContextSaveGState: invalid context 0x0
CGContextSetFillColorWithColor: invalid context 0x0
CGContextAddRect: invalid context 0x0
CGContextDrawPath: invalid context 0x0
CGContextRestoreGState: invalid context 0x0
CGContextRestoreGState: invalid context 0x0
Run Code Online (Sandbox Code Playgroud)

NSR*_*der 5

继续做你的所有绘图-drawRect:.当某些内容发生变化并且您希望重新绘制视图时,请将其发送-setNeedsDisplay-setNeedsDisplayInRect:发送消息.