描画コードをdrawrectから他のメソッドに移動します。ビューのコンテキストにレンダリングする代わりに、画像コンテキストにレンダリングします。このメソッドを描画コードの先頭に追加して、画像コンテキストを作成します。
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 voila、performaceができます!