1、畫直線app
代碼:spa
效果:ast
2、畫三角形class
代碼:
//
// YYrectview.m
// 02-畫三角形
//
// Created by 孔醫己 on 14-6-10.
// Copyright (c) 2014年 itcast. All rights reserved.
//
#import "YYrectview.h"
@implementation YYrectview
- (void)drawRect:(CGRect)rect
{
//1.得到圖形上下文
CGContextRef ctx=UIGraphicsGetCurrentContext();
//2.繪製三角形
//設置起點
CGContextMoveToPoint(ctx, 20, 100);
//設置第二個點
CGContextAddLineToPoint(ctx, 40, 300);
//設置第三個點
CGContextAddLineToPoint(ctx, 200, 200);
//設置終點
// CGContextAddLineToPoint(ctx, 20, 100);
//關閉起點和終點
CGContextClosePath(ctx);
// 3.渲染圖形到layer上
CGContextStrokePath(ctx);
}
@end
效果:
提示:關閉起點和終點 CGContextClosePath(ctx);
3、畫四邊形
代碼:
提示:若是要設置繪圖的狀態必須在渲染以前。
效果(實心和空心):
4、畫圓
代碼1:
- (void)drawRect:(CGRect)rect
{
// 1.獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 畫圓
CGContextAddArc(ctx, 100, 100, 50, 0, 2 * M_PI, 0);
// 3.渲染 (注意, 畫線只能經過空心來畫)
// CGContextFillPath(ctx);
CGContextStrokePath(ctx);
}
效果:
代碼2:
// 畫圓
// 1.獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.畫圓
CGContextAddEllipseInRect(ctx, CGRectMake(50, 100, 50, 50));
[[UIColor greenColor] set];
// 3.渲染
// CGContextStrokePath(ctx);
CGContextFillPath(ctx);
效果:
代碼3:
效果:
5、畫圓弧
代碼1:
// 畫圓弧
// 1.獲取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 2.畫圓弧
// x/y 圓心
// radius 半徑
// startAngle 開始的弧度
// endAngle 結束的弧度
// clockwise 畫圓弧的方向 (0 順時針, 1 逆時針)
// CGContextAddArc(ctx, 100, 100, 50, -M_PI_2, M_PI_2, 0);
CGContextAddArc(ctx, 100, 100, 50, M_PI_2, M_PI, 0);
CGContextClosePath(ctx);
// 3.渲染
// CGContextStrokePath(ctx);
CGContextFillPath(ctx);
效果:
代碼2:
// 1.獲取上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 2.畫餅狀圖 // 畫線 CGContextMoveToPoint(ctx, 100, 100); CGContextAddLineToPoint(ctx, 100, 150); // 畫圓弧 CGContextAddArc(ctx, 100, 100, 50, M_PI_2, M_PI, 0); // CGContextAddArc(ctx, 100, 100, 50, -M_PI, M_PI_2, 1); // 關閉路徑 CGContextClosePath(ctx); [[UIColor brownColor]set]; // 3.渲染 (注意, 畫線只能經過空心來畫) CGContextFillPath(ctx); // CGContextStrokePath(ctx);
效果: