三角のViewを作る方法のメモです。

(iOS5 で試しています。)

ポイント

・CGContext を使って三角のパスを塗りつぶす

・View のバックグラウンドは draw の外で制御する(今回は、init で透明化)

サンプル実装

UIView のサブクラスを使います。

Xcode のメニューから、File -> New -> File と進めて、

Objective-C を選択、「Triangle」という名前のサブクラスを作りました。

「Triangle.m」

@implementation Triangle

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // 背景を透明にする

        self.backgroundColor = [UIColorclearColor];

    }

    returnself;

}

– (void)drawRect:(CGRect)rect

{

    // 塗りつぶす色を設定する。

    [[UIColorgreenColor] setFill];

    

    // 三角形のパスを書く (3点でオープンパスにした。)

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    float width = self.bounds.size.width;

    float height = self.bounds.size.height;

    CGContextMoveToPoint(ctx, width / 2, 0);

    CGContextAddLineToPoint(ctx, width, height);

    CGContextAddLineToPoint(ctx, 0, height);

    

    // 塗りつぶす

    CGContextFillPath(ctx);

}

@end

これを、ViewControllerで使ってみます。

「 ViewController.m 」

#import “Triangle.h”

@implementation ViewController

– (void)viewDidLoad

{

    [superviewDidLoad];

    

    Triangle *triView = [[Triangle alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];

    [self.view addSubview:triView];

}

@end