将您的绘图代码从绘图矩形移到其他方法中。而不是渲染到视图的上下文中,而是渲染到图像上下文中。将此方法添加到绘图代码的开头以创建图像上下文:
UIGraphicsBeginImageContextWithOptions(
CGSize size,
BOOL opaque,
CGFloat scale
);
像这样使用它:
UIGraphicsBeginImageContextWithOptions(
self.bounds.size,
NO, //if you are doing rounded corners or anything, else YES
0.0 //Scales automatically for retina displays
);
//Need a reference to the context you just made?
CGContextRef ctx = UIGraphicsGetCurrentContext();
您的 CG 绘图代码正常工作。然后将上下文渲染为图像
UIImage * renderedImage = UIGraphicsGetImageFromCurrentImageContext();
别忘了
UIGraphicsEndImageContext();
从只需要绘制一次的地方调用这个绘图代码。这些是您可以覆盖的一些候选方法:
- (void)willMoveToSuperview:(UIView *)newSuperview //called when adding to a view
- (void)layoutSubviews //called when first displayed, on frame change and after setNeedsLayout has been called.
然后在视图上设置这些图像。如果你有按钮,你应该有 UIButton 的子类。您现在可以- (void)setImage:(UIImage *)image forState:(UIControlState)state
Et 瞧,表演!