
UIViewにはdrawRectメソッドが実装されていて、これをオーバーライドすることで
直接グラフィック関数を使って描画できる。
まず、UIViewのサブクラスのDrawRectViewを作る。
@interface DrawRectView : UIView {
}
@end
@implementation DrawRectView
- (id)init{
self = [super init];
return self;
}
- (void)drawRect:(CGRect)rect{
// グラフィックを取得
CGContextRef g = UIGraphicsGetCurrentContext();
// 白い四角
CGContextSetRGBFillColor(g, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
// 赤い四角
CGContextSetRGBFillColor(g, 1.0, 0.0, 0.0, 1.0);
CGContextFillRect(g, CGRectMake(self.frame.size.width*0.1, self.frame.size.height*0.1, self.frame.size.width*0.8, self.frame.size.height*0.8));
// 青い四角
CGContextSetRGBFillColor(g, 0.0, 0.0, 1.0, 1.0);
CGContextFillRect(g, CGRectMake(self.frame.size.width*0.2, self.frame.size.height*0.2, self.frame.size.width*0.6, self.frame.size.height*0.6));
// 黒線で×
CGContextSetRGBStrokeColor(g, 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(g);
CGContextMoveToPoint(g, 0, 0);
CGContextAddLineToPoint(g, self.frame.size.width, self.frame.size.height);
CGContextMoveToPoint(g, self.frame.size.width, 0);
CGContextAddLineToPoint(g, 0, self.frame.size.height);
CGContextClosePath(g);
CGContextDrawPath(g, kCGPathStroke);
}
@end
drawRectの中で描画をしている。
描く内容はなんでもよいのですが、
Viewサイズの白い四角、
一回り小さい赤い四角、
さらに一回り小さい青い四角、
そのうえに黒線で×
を描いてみました。
ざっくりした使い方は
CGContextRef g = UIGraphicsGetCurrentContext();
で最初にグラフィックスコンテキストを取得。
その後は、このコンテキストに対してCGContext~関数を使って描画指示を
することで描画できちゃいます

このビューを実装すれば画面に表示されます。
UIView* oya = [[UIView alloc]init];
oya.frame = CGRectMake(0, 0, 320, 480);
DrawRectView* view = [[DrawRectView alloc]init];
view.frame = CGRectMake(0, 0, 320, 480);
[oya addSubview:view];

描画関数を使うと、画像を用意しなくてもいろいろできちゃうので、
活用すると結構便利~

ではでは。