代码都在自定义customView1 的 "- (void)drawRect:(CGRect)rect"方法中进行.
下面就直接贴代码:
step1:初始化创建自定义的view,用于展示.
#import "ViewController.h"
#import "customView1.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorwhiteColor];
customView1 * view1 = [[customView1alloc]initWithFrame:CGRectMake(0,0, [UIScreenmainScreen].bounds.size.width,300)];
view1.backgroundColor = [UIColorgroupTableViewBackgroundColor];
[self.viewaddSubview:view1];
}
@end
当自定义view第一次显示出来的时候就会调用drawRect方法
在drawRect方法中调用UIGraphicsGetCurrentContext方法获取出来的就是Layer的上下文
// Copyright © 2016年 maojing. All rights reserved.
//
#import "customView1.h"
@implementation customView1
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
[self drawRectLine];
// [self drawRectRound];
// [self drawRectCircle];
// [self drawRectEllipse];
}
/**画一个简单的椭圆**/
-(void)drawRectEllipse{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ref, CGRectMake(100, 100, 50, 100));
[[UIColor greenColor] set];
// CGContextStrokePath(ref);
CGContextFillPath(ref);
}
效果:
![]()
/**画简单的圆 或者弧形**/
-(void)drawRectCircle{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddArc(ref, 100,100 , 50, 0, M_PI * 2, 0);//通过设置 开始 和结束 角度 可以画出不同的 扇形
[[UIColor redColor] set];
CGContextSetLineWidth(ref, 3);
// CGContextStrokePath(ref);
CGContextFillPath(ref);
}
效果:
![]()
/**简单四边形**/
-(void)drawRectRound{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddRect(ref, CGRectMake(20, 20, 100, 100));
[[UIColor colorWithRed:100/255.0 green:150/255.0 blue:200/255.0 alpha:1] set];
// CGContextStrokePath(ref);//空心 只有线有颜色
CGContextFillPath(ref);//实心 填充颜色
}
效果:
![]()
/**简单画线**/
-(void)drawRectLine{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ref, 20, 100);
CGContextAddLineToPoint(ref, 300, 100);
CGContextAddLineToPoint(ref, 300, 200);
CGContextAddLineToPoint(ref, 20, 100);
CGContextSetRGBStrokeColor(ref, 0,0.5,0.5,1.0);
CGContextSetLineCap(ref, kCGLineCapRound);
CGContextSetLineJoin(ref, kCGLineJoinRound);
CGContextSetLineWidth(ref, 20);
CGContextStrokePath(ref);
}
效果:
![]()
@end