1)用C语言的方式简单的创建三角形(由线段构成)
//rect:就是view的大小
- (void)drawRect:(CGRect)rect {
// Drawing code
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.添加路径
CGContextMoveToPoint(ctx, 50, 50);
//添加线段
CGContextAddLineToPoint(ctx, 200, 200);
//再添加一根线段
CGContextAddLineToPoint(ctx, 50, 200);
//画三角形
// CGContextAddLineToPoint(ctx, 50, 50);
//关闭路径
CGContextClosePath(ctx);
//3.渲染
CGContextStrokePath(ctx);
NSLog(@"我被调用了");
NSLog(@"%@",NSStringFromCGRect(rect));
}
2)简单的创建一个矩形(1)
- (void) test01
{
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.添加路径
CGContextAddRect(ctx, CGRectMake(50, 50, 200, 200));
//3.渲染
// CGContextStrokePath(ctx);//空心
CGContextFillPath(ctx);//填充
}
3)C语言的方式简单创建矩形(2)
- (void) test02
{
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
UIBezierPath * path = [UIBezierPath bezierPath];
//3.向刚刚创建的路径中添加子路径
[path moveToPoint:CGPointMake(50, 50)];
//3.1 添加线段
[path addLineToPoint:CGPointMake(200, 200)];
//3.2 再加一根线段
[path addLineToPoint:CGPointMake(50, 200)];
//关闭路径
[path closePath];
//4.把刚刚创建的路径添加到图形上下文中
CGContextAddPath(ctx, path.CGPath);//转换为CGPath
//5.渲染
CGContextDrawPath(ctx, kCGPathStroke);
}
4)用OC创建矩形(一)
- (void)drawRect:(CGRect)rect
{
// Drawing code
//创建路径
UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(50, 50, 200, 200)];
//渲染
// [path stroke];
[path fill];
}
5)用OC创建带圆角的矩形
- (void) test01
{
//绘制带圆角的矩形
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(50, 50, 150, 150) cornerRadius:49];
//3.把刚刚创建的路径添加到图形上下文中
CGContextAddPath(ctx, path.CGPath);
//4.渲染
CGContextDrawPath(ctx, kCGPathStroke);
}
6)用OC创建圆
- (void) test02
{
//绘制椭圆
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)];
//3.把刚刚创建的路径添加到图形上下文中
CGContextAddPath(ctx, path.CGPath);
//4.渲染
CGContextDrawPath(ctx, kCGPathStroke);
}
7)用OC创建圆专业写法
- (void)drawRect:(CGRect)rect {
// Drawing code
//绘制圆弧
//1.获取图形上下文对象
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.创建路径
//参数1:圆心 参数2:半径 参数3:起始弧度 参数4:结束弧度 参数5:是否顺时针
//设置圆心
CGPoint centerP = CGPointMake(150, 150);
//设置半径
CGFloat radius = 100;
//设置起始弧度和结束弧度
CGFloat start = 0;
CGFloat end = M_PI * 2;
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:start endAngle:end clockwise:YES];
//连接圆心
// [path addLineToPoint:centerP];
//关闭路径
// [path closePath];
//3.把路径添加到上下文中
CGContextAddPath(ctx, path.CGPath);
//4.渲染
CGContextDrawPath(ctx, kCGPathStroke);
}