プログラマでありたい

おっさんになっても、プログラマでありつづけたい

iPhone/iPadアプリで、角丸矩形を作る方法

 iPhoneのUI作成といえば、基本的にはInterface Builderを使えば問題ありません。ただIBだけでは実現できないことがあるのも事実です。その一つが角丸を作る方法。世の中角丸フェチが結構いるようなので、需要は多いのですがIB単体では角丸を作ることが出来ません。


 ただIBで作ったUIViewやUILabel等を角丸化することは可能です。その為の手順をまとめました。
・プロジェクトのフレームワークにQuartzCore.frameworkを追加する
・"QuartzCore/QuartzCore.h"をインポートする
・対象のオブジェクトに、以下の設定をする
hoge.layer.maskksToBounds = YES;
hoge.layer.cornerRadius = 10;


IB上でこのように見える画像が


このようになります。


ソースはこちら

#import "RoundedCornersViewController.h"
#import "QuartzCore/QuartzCore.h"

@implementation RoundedCornersViewController

@synthesize mainView;


- (void)viewDidLoad {
    [super viewDidLoad];
	mainView.layer.masksToBounds = YES;
	mainView.layer.cornerRadius = 10;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


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

@end
#import "RoundedCornersViewController.h"
#import "QuartzCore/QuartzCore.h"

@implementation RoundedCornersViewController

@synthesize mainView;


- (void)viewDidLoad {
    [super viewDidLoad];
	mainView.layer.masksToBounds = YES;
	mainView.layer.cornerRadius = 10;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


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

@end


 IBのプロパティで設定出来るようになればなぁと思います。QuartzCoreフレームワークを使う為に、IBでは出来ないのだと思うけど。。。