UIViewに図形を直接描画する
UIViewに直接図形を描画するにはコンテキストを使う。
CGContextをゲットして、それに対して図形を描いていく。
今回はUIViewのdrawRectメソッドをオーバーライドして描画してみる。
|
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 背景色を透明に
self.backgroundColor = UIColor.clearColor;
}
return self;
}
/**
* UIViewを描画する時に呼ばれる
*/
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
// 6色
UIColor *colors[6] = {
UIColor.redColor,
UIColor.orangeColor,
UIColor.yellowColor,
UIColor.greenColor,
UIColor.blueColor,
UIColor.purpleColor,
};
CGRect r = self.bounds;
int width = 20;
int offset = 10;
// コンテキストをゲット
CGContextRef context = UIGraphicsGetCurrentContext();
// 線の幅を設定
CGContextSetLineWidth(context, width);
for (int i = 0; i < 6; i++) {
// 線の色を設定
CGContextSetStrokeColorWithColor(context, colors[i].CGColor);
// 書き出し位置に移動
CGContextMoveToPoint(context, offset, r.size.height);
// 弧の位置を設定
CGContextAddArcToPoint(context, offset, offset, r.size.width, offset, r.size.width - offset);
// パスを描画
CGContextStrokePath(context);
offset += width;
}
} |
上のコードを実装したUIViewを正方形で設置するとこんな風に表示がされる。
ついでにこれを使ってUIViewControllerでアニメーションを実装してみる。
以下のコードを実装する。
|
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
/**
* 虹をフェードアウトさせる
* 1.2秒待って
* 2.2秒かけて透明度を0にする
*/
- (void)fadeoutView {
// アニメーション設定開始
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2.0];
[UIView setAnimationDelay:2.0];
// 透明度0
_rainbowView.alpha = 0.0;
// アニメーションをコミット
[UIView commitAnimations];
}
/**
* 虹を表示させる
* 1.透明度を1にもどす
*/
- (void)resetView {
// 透明度を戻す
_rainbowView.alpha = 1.0;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.whiteColor;
// 正方形で下に設置する
CGRect rect = self.view.bounds;
rect.origin.y = rect.size.height - rect.size.width;
rect.size.height = rect.size.width;
_rainbowView = [[RainbowView alloc] initWithFrame:rect];
[self.view addSubview:_rainbowView];
[self fadeoutView];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[_rainbowView release];
[super dealloc];
}
/**
* タッチイベント開始
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
// 虹を表示する
[self resetView];
}
/**
* タッチ移動
*/
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
}
/**
* タッチイベント終了
*/
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
// 虹をフェードアウトする
[self fadeoutView];
} |
放っておくと虹が消えて、タッチをすると虹がまた現れる。
