2011年5月27日金曜日

Core Graphicsで図形を描く

まーるさんかくしかーくー♪
ってことで、今回は図形を描写します。

まずこれ。簡単な四角形から。





-(void)drawInContext:(CGContextRef)context
{
CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);

CGContextStrokeRect(context, CGRectMake(20.0, 20.0, 100.0, 200.0));

}
CGContextStrokeRect(context, CGRect);で枠だけの四角を描く。

次にこれ
-(void)drawInContext:(CGContextRef)context
{
CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);

CGRect rect = CGRectMake(20.0, 20.0, 200.0, 300.0);
CGContextStrokeRectWithWidth(context, rect,10.0);

}

CGContextStrokeRectWithWidth(context, rect,線の太さ);で線の太さを変更できる四角を描く

次にこれ

-(void)drawInContext:(CGContextRef)context
{
CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);

CGRect rect = CGRectMake(20.0, 20.0, 200.0, 300.0);
CGContextFillRect(context, rect);

}

はい、真っ黒〜
CGContextSetRGBStrokeColorは線の色なので、下の塗りつぶし色の設定を追加します。
CGContextSetRGBFillColor(context, 1.0, 0, 0, 1.0);



再び実行。
まさにRectを塗りつぶした形になります。




次に丸を描いてみます。

CGContextAddEllipseInRect(context,rect);//線の円
CGContextFillEllipseInRect(context,rect);//塗りつぶされた円
CGContextAddEllipseInRect(context,rect);//パスを追加

これも分かりやすいですね。


三角形はどうしょうでしょうか。
特にそれ用の関数は無いので、線を引いてその中を埋めていきます。


CGContextMoveToPoint(context,160.0,10.0);
CGContextAddLineToPoint(context,10.0,200.0);
CGContextAddLineToPoint(context,310.0,200.0);
CGContextFillPath(context);//塗りつぶす


この書き方だと、複数図形があってそれぞれ異なる色で塗りつぶしたり、はたまた線だけの図形を描くときにどうするんだろう?
で、一回一回完結させてみた。

-(void)drawInContext:(CGContextRef)context
{

CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1.0);
CGContextSetRGBFillColor(context, 0, 1.0, 0, 1.0);

CGContextMoveToPoint(context,160.0,10.0);
CGContextAddLineToPoint(context,10.0,200.0);
CGContextAddLineToPoint(context,310.0,200.0);


CGContextFillPath(context);

CGContextStrokeEllipseInRect(context, CGRectMake(10, 200, 100, 100));

CGRect rect = CGRectMake(10,210 , 100, 100);
CGContextAddEllipseInRect(context,rect);
CGContextStrokePath(context);

CGContextSetRGBFillColor(context, 1.0, 1.0, 0, 1.0);
CGContextFillEllipseInRect(context,CGRectMake(200,200,100,200));

}



とりあえず図形についてはこれでおしまい。

0 件のコメント:

コメントを投稿