絶対に挫折しないiPhoneアプリ開発入門Part.29 ~UIViewを使って簡単に線を描画する~

前回:絶対に挫折しないiPhoneアプリ開発入門Part.28 ~【iOS5】Twitterフレームワークを入れて投稿してみよう~


Part.29では、

単純に線を描く

ということをやります。


ただただ単純に、線を描画します。


SingleViewApplicationからスタートします。

  • プロジェクトの名前はStrokeSample
  • Storyboardにチェックは入れない(今回は使わない)
  • ARCにチェックを入れる
  • UnitTestにチェックは入れない


Storyboardにチェックを入れずにSingleViewApplicationからスタートすると、
xibが生成されています。


UIViewサブクラスでファイルを新規作成

UIViewサブクラスで新しいクラスをつくりましょ!


Objective-C classを選択、Next

Classの名前は「BlackStroke」、Subclass of 「UIView」ですね。


こんな感じで追加できましたか?

UIViewのdrawRectで描画する

- (void)drawRect:(CGRect)rect」というメソッドを使います。

drawRectのメソッドは最初コメントアウトされている状態なので、コメント部分を消します。

// /*←これを消す
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
// */←これを消す

すると、BlackStroke.mはこういう状態

#import "BlackStroke.h"

@implementation BlackStroke

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}


@end

UIViewの背景色を透明にする

UIViewをaddSubviewするので、UIViewControllerの上に透明の薄い膜をのせるイメージでしょうか。

BlackStroke.mにinitWithFrameにviewの背景が透明であるというコードを書きましょう。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = UIColor.clearColor; //背景を透明に
    }
    return self;
}

UIGraphicsを使って描画 UIGraphicsGetCurrentContext()

drawRectで描きましょう♫

BlackStroke.m

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();  // コンテキストを取得
    
    // 線を黒色にする
    CGContextSetStrokeColorWithColor(context,UIColor.blackColor.CGColor);
    
    
    // 線の太さを指定
    CGContextSetLineWidth(context, 10.0);  // 10ptに設定
    
    CGContextMoveToPoint(context, 50, 100);  // 始点
    CGContextAddLineToPoint(context, 100, 200); // 終点
    CGContextStrokePath(context);  // 描画
}


図解します。

イメージが大切です!



UIViewをUIViewControllerにaddSubviewする

まずはBlackStroke.hをインポート

ViewController.m

#import "ViewController.h"
#import "BlackStroke.h" //<-追加


BlackStrokeクラスのインスタンスを作成して、フレームを初期化で設定した後、addSubviewですね。

- (void)viewDidLoad
{
    [super viewDidLoad];
    BlackStroke *bs = [[BlackStroke alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:bs];
}


実行!



というわけで、簡単に線を描画することができました。