Quartz2D
苹果封装的一套绘图的函数库,同时支持iOS
和Mac
. UIKit框架,里面有各种各样的UI控件,其实大部分控件的内容都是通过Quartz2D
画出来的
Quartz2D能做什么?
- 绘制图形 : 线条\三角形\矩形\圆\弧等
- 绘制文字
- 绘制\生成图片(图像)
- 读取\生成PDF
- 截图\裁剪图片
- 自定义UI控件
- 涂鸦\画板
- 手势解锁
...........
iOS中常用的是截屏/裁剪/自定义UI控件
Quartz2D使用须知
Quartz2D的API是纯C语言的,来自于Core Graphics框架
数据类型和函数基本都以CG作为前缀
CGContextRef //图形上下文
CGPathRef //路径
CGContextStrokePath(ctx); //渲染
利用Quartz2D绘制东西到view上的步骤
1. 新建一个类,继承自UIView
//在drawRect:方法中才能取得跟view相关联的图形上下文
//当view第一次显示到屏幕上时(被加到UIWindow上显示出来)
调用view的setNeedsDisplay或者setNeedsDisplayInRect:时
2. 实现- (void)drawRect:(CGRect)rect方法,然后在这个方法中
3. 取得跟当前view相关联的图形上下文
4. 绘制相应的图形内容
5. 利用图形上下文将绘制的所有内容渲染显示到view上面
总结 在drawRect 绘图的步骤
1. 获取图形上下文
2. 绘图操作
3. 渲染
绘图方式
——————————使用不同方式绘图——————————
- 直接使用图形上下文画图 C
// 获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//2.描述路径
//2.1 创建路径
CGContextMoveToPoint(ctx, 10, 10);
//2.2 添加线到一个点
CGContextAddLineToPoint(ctx, self.bounds.size.width-10, self.bounds.size.height-10);
CGContextMoveToPoint(ctx, self.bounds.size.width-10, 10);
CGContextAddLineToPoint(ctx, 10, self.bounds.size.height-10);
//设置绘图颜色
[[UIColor grayColor] set];
CGContextSetLineWidth(ctx, 10);
// 连接处的样式
// kCGLineJoinMiter, // 默认
// kCGLineJoinRound, // 圆角
// kCGLineJoinBevel // 切角
CGContextSetLineJoin(ctx, kCGLineJoinRound);
// 设置线的头部方式
// 头尾的样式
// kCGLineCapButt, // 默认
// kCGLineCapRound, // 圆角
// kCGLineCapSquare // 会比默认的样式两边各多一个线宽/2的距离
CGContextSetLineCap(ctx, kCGLineCapRound);
//3.完成路线
CGContextStrokePath(ctx);
- 图形上下文 + CGPathRef画线 C
//1.获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 使用path画线
CGMutablePathRef path = CGPathCreateMutable();
// 添加点
CGPathMoveToPoint(path, nil, 0, 0);
CGPathAddLineToPoint(path, nil, self.bounds.size.width, self.bounds.size.height);
CGPathMoveToPoint(path, NULL, self.bounds.size.width, 0);
CGPathAddLineToPoint(path, NULL, 0, self.bounds.size.height);
CGContextAddPath(ctx, path);
CGContextStrokePath(ctx);
- 贝塞尔曲线 OC 这个很方便
// 创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(self.bounds.size.width, self.bounds.size.height)];
[path moveToPoint:CGPointMake(self.bounds.size.width, 0)];
[path addLineToPoint:CGPointMake(0,self.bounds.size.height)];
[path stroke];
- 图形上下文 + 贝塞尔曲线 c_+OC
// 获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 0)];
[path addLineToPoint:CGPointMake(self.bounds.size.width, self.bounds.size.height)];
[path moveToPoint:CGPointMake(self.bounds.size.width, 0)];
[path addLineToPoint:CGPointMake(0, self.bounds.size.height)];
// ----------------这二句话相当于 UIBezierPath 的 stroke吧
CGContextAddPath(ctx, path.CGPath);
CGContextStrokePath(ctx);
// ---------------------------
——————————使用不同方式绘图 以上——————————
绘制一些图形
- 画三条线,并且设置属性
//1.获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 100, 100);
CGContextAddLineToPoint(ctx, 200, 200);
CGContextAddLineToPoint(ctx, 300, 100);
//设置绘图颜色
[[UIColor grayColor] set];
CGContextSetLineWidth(ctx, 10);
//设置链接外的链接类型
CGContextSetLineJoin(ctx, kCGLineJoinRound);
//设置线的头部方式
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextStrokePath(ctx);
// 绘制属性不同的线
CGContextRef ctx2 = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx2, 0, 0);
CGContextAddLineToPoint(ctx2, 100, 100);
[[UIColor greenColor] set];
CGContextSetLineWidth(ctx2, 10);
CGContextStrokePath(ctx2);
- 绘制两条不相交的线,并且设置各自属性 贝塞尔曲线
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(100, 100)];
[path addLineToPoint:CGPointMake(300, 150)];
[[UIColor redColor] set];
[path setLineWidth:7];
[path stroke];
UIBezierPath *path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointMake(100, 200)];
[path2 addLineToPoint:CGPointMake(300, 250)];
[[UIColor greenColor] set];
[path2 setLineWidth:2];
[path2 setLineCapStyle:kCGLineCapRound];
[path2 stroke];
- 绘制曲线
// 获得图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 50, 50);
// * @param c#> 图形上下文
// * @param cpx#> 将来要突出的x值
// * @param cpy#> 要突出的y值
// * @param x#> 曲线结束时的x
// * @param y#> 曲线结束时的y
CGContextAddQuadCurveToPoint(ctx, 200, 400, 350, 50);
//设置颜色
[[UIColor redColor] set];
//设置宽度
CGContextSetLineWidth(ctx, 5);
//3.渲染图层
CGContextStrokePath(ctx);
- 一些图形
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 50, 100, 40) cornerRadius:5];
[[UIColor redColor] set];
[path stroke];
UIBezierPath *path2 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 140, 100, 100) cornerRadius:5];
[[UIColor greenColor] set];
[path2 fill];
UIBezierPath *path3 = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(10, 290, 100, 100) cornerRadius:50];
[[UIColor blueColor] set];
[path3 fill];
- 绘制一个弧度曲线
// * 绘制弧度曲线
// *
// * @param ArcCenter 曲线中心
// * @param radius 半径
// * @param startAngle 开始的弧度
// * @param endAngle 结束的弧度
// * @param clockwise YES顺时针,NO逆时针
//绘制一条半圆曲线
// 1.M_PI是180度.M_PI_2是90°
// 2.这里的角度都是弧度制度,如果我们需要15°,可以用15°/180°*π得到。
// 3.clockwise这个是顺时针,如果穿1,就是顺时针,穿0,是逆时针
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:50 startAngle:0 endAngle:M_PI clockwise:YES];
[[UIColor redColor] set];
[path setLineWidth:20];
[path setLineCapStyle:kCGLineCapRound];
[path stroke];
//绘制一条3/4圆曲线
UIBezierPath *path2 = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 350) radius:50 startAngle:0 endAngle:270/360.0*(M_PI * 2) clockwise:YES];
[[UIColor purpleColor] set];
[path2 setLineWidth:10];
[path2 setLineCapStyle:kCGLineCapRound];
[path2 stroke];
UIBezierPath *path3 = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 550) radius:50 startAngle:0 endAngle:(M_PI * 2) clockwise:YES];
[[UIColor greenColor] set];
[path3 setLineWidth:10];
[path3 setLineCapStyle:kCGLineCapRound];
[path3 stroke];
- 绘制一个一个扇形
CGContextRef ctx = UIGraphicsGetCurrentContext();
//绘制曲线
CGFloat centerX = 100;
CGFloat centerY = 100;
CGFloat radius = 50;
CGContextMoveToPoint(ctx, centerX, centerY);
CGContextAddArc(ctx, centerX, centerY, radius, M_PI, (230 / 360.0)*(M_PI * 2), NO);
CGContextClosePath(ctx);
// 渲染
CGContextFillPath(ctx);
- 文字绘到屏幕上
NSString *str = @"在sourceTree中找到需要提交的分支\n在显示提交信息中,选择所有分支,这样子就会出现所\n有分支的修改信息。\n找到需要合并的某次修\n改信息,点击,右键会出现弹框";
//设置文字的属性
NSMutableDictionary * paras = [NSMutableDictionary dictionary];
//设置字体大小
paras[NSFontAttributeName] = [UIFont systemFontOfSize:40];
//设置字体颜色
paras[NSForegroundColorAttributeName] = [UIColor blackColor];
//设置镂空渲染颜色
paras[NSStrokeColorAttributeName] = [UIColor orangeColor];
// 创建阴影对象
NSShadow *shadow = [[NSShadow alloc] init];
// 阴影颜色
shadow.shadowColor = [UIColor redColor];
// 阴影偏移量
shadow.shadowOffset = CGSizeMake(5, 6);
// 阴影的模糊半径
shadow.shadowBlurRadius = 4;
// 苹果的富文本是这样搞出来的?
paras[NSShadowAttributeName] = shadow;
[str drawAtPoint:CGPointZero withAttributes:paras];
- 饼状图
PieChartView.h
@interface YLPieChart : UIView
//总和
@property (nonatomic,retain) NSArray *nums;
@end
PieChartView.m
@interface YLPieChart()
@property (nonatomic,assign) NSInteger total;
@end
@implementation YLPieChart
- (NSInteger)total
{
if (_total == 0) {
for (int i = 0; i < self.nums.count ; i ++) {
_total += [self.nums[i] integerValue];
}
}
return _total;
}
- (void)drawRect:(CGRect)rect {
CGFloat radius = 150;
CGFloat startA = 0;
CGFloat endA = 0;
for (int i = 0; i < self.nums.count; i++) {
NSNumber *num = self.nums[I];
startA = endA;
endA = startA + [num floatValue]/self.total * (2 * M_PI);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:self.center radius:radius startAngle:startA endAngle:endA clockwise:YES];
[path addLineToPoint:self.center];
CGFloat randRed = arc4random_uniform(256)/255.0;
CGFloat randGreen = arc4random_uniform(256)/255.0;
CGFloat randBlue = arc4random_uniform(256)/255.0;
UIColor *randomColor = [UIColor colorWithRed:randRed green:randGreen blue:randBlue alpha:1];
[randomColor set];
[path fill];
}
}
ViewController.m
@interface ViewController ()
@property(nonatomic,strong)YLPieChart *pieChart;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addSubview:self.pieChart];
}
- (YLPieChart *)pieChart {
if (!_pieChart) {
_pieChart =[[YLPieChart alloc] initWithFrame:self.view.bounds];
_pieChart.backgroundColor = [UIColor whiteColor];
_pieChart.nums = @[@"10",@"20",@"30",@"40",@"50",@"60"];
}
return _pieChart;
}
- 柱状图
HistogramView.h
@interface YLHistogramView : UIView
@property(nonatomic,strong)NSArray *nums;
@end
HistogramView.m
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat margin = 30;
if (self.nums.count > 5) {
margin = 10;
}
//柱状图的宽度 = ( view的宽度 - 间隔的总宽度 )/ 柱状图的个数
CGFloat width = (rect.size.width - (self.nums.count + 1) *margin) / self.nums.count;
for (int i = 0; i < self.nums.count; i++) {
//求出 每一个数字所占的比例
CGFloat num = [self.nums[i] floatValue]/100;
//起点位置
CGFloat x = margin + (width + margin) * I ;
CGFloat y = rect.size.height * (1 - num);
CGFloat height = rect.size.height * num;
CGRect rectA = CGRectMake(x, y, width, height);
CGContextAddRect(ctx, rectA);
CGFloat randRed = arc4random_uniform(256)/255.0;
CGFloat randGreen = arc4random_uniform(256)/255.0;
CGFloat randBlue = arc4random_uniform(256)/255.0;
UIColor *randomColor = [UIColor colorWithRed:randRed green:randGreen blue:randBlue alpha:1];
[randomColor set];
//渲染
CGContextFillPath(ctx);
}
}
ViewController.m
@interface ViewController ()
@property(nonatomic,strong)YLHistogramView *myView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.myView];
}
- (YLHistogramView *)myView {
if (!_myView) {
_myView = [[YLHistogramView alloc] initWithFrame:self.view.bounds];
_myView.backgroundColor = [UIColor whiteColor];
_myView.nums = @[@"10",@"20",@"30",@"40",@"50"];
}
return _myView;
}
- 控件关联绘图
CustomProgressView.h
@interface CustomProgressView : UIView
@property (nonatomic,assign) CGFloat progressValue;
@end
CustomProgressView.m
- (void)setProgressValue:(CGFloat)progressValue {
_progressValue = progressValue;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:self.center radius:100 startAngle:-M_PI_2 endAngle:(_progressValue / 100.0) * (2 * M_PI) -M_PI_2 clockwise:YES];
[[UIColor redColor] set];
[path setLineWidth:10];
[path setLineCapStyle:kCGLineCapRound];
[path stroke];
}
ViewController.m
#import "CustomProgressView.h"
@interface ViewController ()
@property(nonatomic,strong)UISlider *slider;
@property(nonatomic,strong)CustomProgressView *progressView;
@property(nonatomic,strong)UILabel *label;
@end
@implementation ViewController
#pragma mark - life cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.progressView];
[self.view addSubview:self.slider];
[self.view addSubview:self.label];
}
#pragma mark - public methods
#pragma mark - private methods
- (void)changeValue:(UISlider *)sender
{
NSLog(@"%d",sender.value);
self.progressView.progressValue = sender.value;
self.label.text = [NSString stringWithFormat:@"%.f%%",sender.value];
}
#pragma mark - getter && setter
#pragma mark - lazy loading
- (UISlider *)slider {
if (!_slider) {
_slider = [[UISlider alloc] initWithFrame:CGRectMake(10, 500, self.view.frame.size.width - 20, 50)];
_slider.minimumValue = 0;
_slider.maximumValue = 100;
[self.slider addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventValueChanged];
}
return _slider;
}
- (CustomProgressView *)progressView {
if (!_progressView) {
_progressView = [[CustomProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
_progressView.backgroundColor = [UIColor whiteColor];
}
return _progressView;
}
- (UILabel *)label {
if (!_label) {
_label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
_label.center = self.progressView.center;
_label.textAlignment = NSTextAlignmentCenter;
}
return _label;
}
- 图形上下文矩阵
使用代码绘制的图形都是很规范的圆是圆,方是方。但是如果有个性的你,想要绘制不符常规的图形,那么需要用到 偏移量 旋转 缩放
- (void)drawRect:(CGRect)rect {
// 1. 获取上下文
CGContextRef ref = UIGraphicsGetCurrentContext();
// 旋转
// CGContextRotateCTM(ref, M_PI_4);
// 缩放
// CGContextScaleCTM(ref, 1, 0.5);
// 平移
// CGContextTranslateCTM(ref, 150, 150);
// 2. 创建路径
CGMutablePathRef path = CGPathCreateMutable();
// 路径操作
CGPathAddArc(path, NULL, 150, 150, 100, 0, 2 * M_PI, 1);
CGPathMoveToPoint(path, NULL, 0, 0);
CGPathAddLineToPoint(path, NULL, self.bounds.size.width, self.bounds.size.height);
CGPathMoveToPoint(path, NULL, self.bounds.size.width, 0);
CGPathAddLineToPoint(path, NULL, 0, self.bounds.size.height);
// 3. 添加路径到上下文
CGContextAddPath(ref, path);
CGContextSetLineWidth(ref, 10);
// 4。 渲染
CGContextStrokePath(ref);
}
- 自定义view模拟imageView
YLView.h
#import <UIKit/UIKit.h>
@interface YLView : UIView
@property(nonatomic,strong)UIImage *image;
- (instancetype)initWithImage:(UIImage *)image;
@end
YLView.m
#import "YLView.h"
@implementation YLView
- (instancetype)initWithImage:(UIImage *)image {
self = [super initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
if (self) {
self.image = image;
}
return self;
}
- (void)setImage:(UIImage *)image {
_image = image;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[self.image drawInRect:rect];
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
YLView *view =[[YLView alloc] initWithImage:[UIImage imageNamed:@"2018"]];
view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:view];
}
- 裁剪渲染区域
- (void)drawRect:(CGRect)rect
{
// 获取图片对象
UIImage* image = [UIImage imageNamed:@"2018"];
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 1.先画出来显示的区域
// CGContextAddArc(ctx, 150, 150, 150, 0, 2 * M_PI, 1);
CGContextAddRect(ctx, CGRectMake(0, 0, 150, 150));
CGContextAddRect(ctx, CGRectMake(150, 150, 150, 150));
// CGContextFillPath(ctx);
// 2.裁剪
CGContextClip(ctx);
// 拉伸显示到 view 上
[image drawInRect:rect];
}
- 图片上下文操作
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 150, 300, 300)];
_imageView.image = [UIImage imageNamed:@"2018"];
[self.view addSubview:_imageView];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self text5];
}
//开启图片上下文
//3步骤
//1. // 开启图片类型的图形上下文
//2. // 通过图片类型的图形上下文 获取图片对象
//3. // 关闭图片类型的图形上下文
- (void)text {
// 开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), NO, 0);
// 获取当前的上下文(图片类型)
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 0, 0);
CGContextAddLineToPoint(ctx, 300, 300);
CGContextSetLineWidth(ctx, 10);
CGContextStrokePath(ctx);
// 通过图片类型的图形上下文 获取图片对象
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 2.关闭图片类型的图形上下文 UIGraphicsEndImageContext();
self.imageView.image = image;
}
//获取裁剪的图片
- (void)text2 {
UIImage *image = [UIImage imageNamed:@"2018"];
// 开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddArc(ctx, image.size.width/2, image.size.height/2, image.size.width/2, 0, 2*M_PI, 1);
// 裁剪
CGContextClip(ctx);
[image drawAtPoint:CGPointZero];
// 取出来 裁剪过的image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 2.关闭图片类型的图形上下文
UIGraphicsEndImageContext();
self.imageView.image = newImage;
}
// 图片添加圆环 感觉还是使用 image 的 cornerRadius 加设置border简单的多
- (void)text3 {
UIImage *image = [UIImage imageNamed:@"2018"];
CGFloat margin = 5;
// 计算图片类型的图形上下文的大小
CGSize ctxSize = CGSizeMake(image.size.width + 2 * margin, image.size.height + 2 * margin);
// 开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(ctxSize, NO, 0);
// 获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//计算圆心
CGPoint arcCenter = CGPointMake(ctxSize.width * 0.5, ctxSize.height * 0.5);
// 计算半径
CGFloat radius = (image.size.width + margin) * 0.5;
// 画圆环
CGContextAddArc(ctx, arcCenter.x, arcCenter.y, radius, 0, 2 * M_PI, 1);
// 设置宽度
CGContextSetLineWidth(ctx, margin);
// 渲染圆环
CGContextStrokePath(ctx);
//画头像显示的区域
CGContextAddArc(ctx, arcCenter.x, arcCenter.y, image.size.width * 0.5, 0, 2 * M_PI, 1);
//裁剪显示区域
CGContextClip(ctx);
//画图片
[image drawAtPoint:CGPointMake(margin, margin)];
// 获取图片
image = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = image;
}
//添加水印 水印可以是文字和图片
- (void)text4 {
UIImage *image = [UIImage imageNamed:@"2018"];
// 1.开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
// 6.画大图
[image drawAtPoint:CGPointZero];
// 需要绘制的文字
NSString *str = @"无印良品";
// 5.画文字水印
[str drawAtPoint:CGPointMake(100, 130) withAttributes:@{ NSFontAttributeName : [UIFont systemFontOfSize:40] }];
//// 图片
// UIImage* logo = [UIImage imageNamed:@"2017"];
//
// 画图片水印
// [logo drawAtPoint:CGPointMake(image.size.width * 0.5, image.size.height * 0.5)];
// 取图片
image = UIGraphicsGetImageFromCurrentImageContext();
self.imageView.image = image;
}
- (void)text5 {
// 开启图片类型的图形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
// 获取图片类型上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 截图 把view 的内容 放到上下文中 然后 渲染
[self.view.layer renderInContext:ctx];
// 取图片
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
// 保存到相册
UIImageWriteToSavedPhotosAlbum(image, NULL, NULL, NULL);
}
@end