忍者ブログ
  • 2024.04
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 2024.06
[PR]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

【2024/05/21 15:35 】 |
5分でCoreGraphicsで描画する
CoreGraphicsで描画するまでの流れ。
5分あればイケます。


///////////////////////////////////
手順1.
プロジェクトの作成。

○XCodeの新規プロジェクトからView-based Projectを選択する。
プロジェクト名は、SimpleCoreGraphicsとしておきます。

自動で生成されているファイル構成は

SimpleCoreGraphicsAppDelegate.m/h
SimpleCoreGraphicsViewController.m/h
SimpleCoreGraphics_Prefix.pch
main.m
である。
拡張子が.mのファイルは、すべて.mmに直しておく。(C++表現がコンパイルを通るようにするため)


///////////////////////////////
手順2.
ビューの作成

○ファイルSimpleCoreGraphicsView.mm/hの作成
ビューの名前は SimpleCoreGraphicsViewとしておきます。

○ファイルSimpleCoreGraphicsView.h

@interface SimpleCoreGraphicsView : UIView {

}

@end

SimpleCoreGraphicsViewを宣言。
UIViewを継承すること


○ファイルSimpleCoreGraphics.mm

#import "SimpleCoreGraphicsView.h"

@implementation SimpleCoreGraphicsView

-(id) initWithFrame:(CGRect) rect
{
if ((self = [super initWithFrame:rect])){

}
return self;
}

-(void) dealloc
{
[super dealloc];
}
@end

初期化関数、破棄関数を定義


○ファイルSimpleCoreGraphicsViewController.mm

#import "SimpleCoreGraphicsView.h"

- (void)loadView {
CGRect screenBounds = [[UIScreen mainScreen] applicationFrame];
self.view = [[SimpleCoreGraphicsView alloc] initWithFrame:screenBounds];
}

SimpleCoreGraphicsViewを生成し、ビューにセットする。


この状態でビルド・実行すると、ビューができるので一面真っ白になる。


///////////////////////////////////
手順3.カレントコンテキストに描画

○カレントコンテキストに直接、描きたい図形を描く。
ファイルCoreGraphicsView.mm

- (void)drawRect:(CGRect)rect
{
//コンテキスト取得
CGContextRef ctxScreen = UIGraphicsGetCurrentContext();

//クリア
CGContextClearRect(ctxScreen, CGRectMake(0, 0, 320, 480));

//直線描画
CGContextSetRGBStrokeColor(ctxScreen, 1.f, 0.f, 1.f, 1.f);
CGContextSetLineWidth(ctxScreen, 5.f);
CGContextSetLineCap(ctxScreen, kCGLineCapRound);

CGContextBeginPath(ctxScreen);
CGContextMoveToPoint(ctxScreen, 10, 10);
CGContextAddLineToPoint(ctxScreen, 50, 50);
CGContextStrokePath(ctxScreen);
}

メソッドdrawRectはUIViewで宣言されているので、オーバーライドする。
drawRectは、最初に自動で1回だけ呼ばれる。その後明示的に呼び出したい場合は、
[self setNeedsDisplay];
と記述する。このメソッドはUIViewで宣言されている。
カレントコンテキストは、UIGraphicsGetCurrentContext()で取得できる。
このコンテキストはview(つまりself)に紐づいており、viewが変化すれば、コンテキストや描画位置も応じて変化する。


完成!
画面に直線が引かれたら成功です。

PR
【2011/03/18 16:44 】 | iPhone | 有り難いご意見(0) | トラックバック()
<<CoreGraphicsで自前のコンテキストを使う | ホーム | 矩形構造体と描画>>
有り難いご意見
貴重なご意見の投稿














虎カムバック
トラックバックURL

<<前ページ | ホーム | 次ページ>>