Skip to content

Instantly share code, notes, and snippets.

@hirokim
Created February 25, 2015 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokim/d4d2bbcca66b629052e5 to your computer and use it in GitHub Desktop.
Save hirokim/d4d2bbcca66b629052e5 to your computer and use it in GitHub Desktop.
iOSで円グラフ描画
/**
* 円グラフ描画
*
*/
- (void)drawGradCircle:(CGRect)dirtyRect context:(CGContextRef)context {
[[UIColor whiteColor] set];
// 画面サイズの小さい方の長さ
float dim = MIN(self.bounds.size.width, self.bounds.size.height);
// 円にする台形の数
int subdiv = 512;
// 内側の円の半径
float r = dim / 4;
// 外側の円の半径
float R = dim / 2;
// 内側の円の円周の長さ
float halfinteriorPerim = 2 * M_PI * r;
// 外側の円の円周の長さ
float halfexteriorPerim = 2 * M_PI * R;
// 内側の円周を台形の数で割って、台形の上底の長さを算出
float smallBase = halfinteriorPerim/subdiv;
// 外側の円周を台形の数で割って、台形の下底の長さを算出
float largeBase = halfexteriorPerim/subdiv;
// 台形のパスを作成
UIBezierPath *cell = [UIBezierPath bezierPath];
[cell moveToPoint: CGPointMake(-smallBase / 2, r)];
[cell addLineToPoint:CGPointMake( smallBase / 2, r)];
[cell addLineToPoint:CGPointMake( largeBase / 2, R)];
[cell addLineToPoint:CGPointMake(-largeBase / 2, R)];
[cell closePath];
// 円周を台形の数で割る
float incr = 2 * M_PI / subdiv;
// 描画領域の原点を画面の真ん中に移動
CGContextTranslateCTM(context, self.bounds.size.width / 2, self.bounds.size.height / 2);
// 描画領域のサイズ調整
CGContextScaleCTM(context, 0.9, 0.9);
// 描画領域を180度回転(真下から台形を描画してしまうのを真上からにする)
CGContextRotateCTM(context, M_PI);
// 描画領域を回転(台形の半分だけ右回転)
CGContextRotateCTM(context, incr / 2);
// 台形の数だけ描画
for (int i = 0; i < temp; i++) {
// 台形の色
[[UIColor colorWithHue:(float)i / subdiv saturation:1 brightness:1 alpha:1] set];
// 台形の枠線を描画
[cell stroke];
// 台形を塗りつぶし
[cell fill];
// 描画領域を台形の分だけ右回転
CGContextRotateCTM(context, incr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment