CoreGraphics 簡介:
CoreGraphics:核心繪圖框架颗品,類名以CG開頭的都屬于這個框架趾徽,它提供的都是C語言的接口朽缎,屬于跨平臺類庫惨远,可以應(yīng)用于iOS和macOS系統(tǒng),與UIKit區(qū)分话肖。
首先來看一下這個類庫中都有哪些類北秽,以便于對這個框架有一個整體的了解(甚至您會發(fā)現(xiàn),自己還不知道平時用到的很多類都出自這個類庫中)最筒。
來到CoreGraphics.h看一下CoreGraphics庫所包含的類
#include <CoreGraphics/CGBase.h> 定義類本庫中的一些宏和配置
#include <CoreGraphics/CGAffineTransform.h> 包含一些形變方法贺氓,比如我們經(jīng)常用到的CGAffineTransformMake(
#include <CoreGraphics/CGBitmapContext.h> 位圖繪制環(huán)境
#include <CoreGraphics/CGColor.h> 繪圖顏色,區(qū)分UIColor床蜘、CIColor
#include <CoreGraphics/CGColorConversionInfo.h>定義顏色的一組組件辙培,帶有指定如何解釋它們的顏色空間。
#include <CoreGraphics/CGColorSpace.h> 指定如何解釋用于顯示的顏色值的配置文件悄泥。
#include <CoreGraphics/CGContext.h> 2D繪圖會話
#include <CoreGraphics/CGDataConsumer.h> 內(nèi)存寫入管理
#include <CoreGraphics/CGDataProvider.h> 內(nèi)存讀取管理
#include <CoreGraphics/CGError.h> 錯誤分析
#include <CoreGraphics/CGFont.h> 2D繪圖字體
#include <CoreGraphics/CGFunction.h> 定義和使用回調(diào)函數(shù)的通用工具
#include <CoreGraphics/CGGeometry.h> 2D幾何原語的各種結(jié)構(gòu)和相關(guān)函數(shù)虏冻。
#include <CoreGraphics/CGGradient.h> 用于繪制徑向和軸向漸變填充的顏色的平滑過渡的定義。
#include <CoreGraphics/CGImage.h> 返回紋理的圖像數(shù)據(jù)作為一個Quartz 2D圖像弹囚。
#include <CoreGraphics/CGLayer.h> 一個幕后上下文厨相,用于重用以核心圖形繪制的內(nèi)容。
#include <CoreGraphics/CGPDFArray.h> 封裝了一個PDF數(shù)組的不透明類型鸥鹉。
#include <CoreGraphics/CGPDFContentStream.h> 一種不透明的類型蛮穿,它提供對描述PDF頁面外觀的數(shù)據(jù)的訪問。
#include <CoreGraphics/CGPDFContext.h> 操作PDF的會話
#include <CoreGraphics/CGPDFDictionary.h> 封裝了一個PDF字典的類型毁渗。
#include <CoreGraphics/CGPDFDocument.h> 包含PDF的文檔
#include <CoreGraphics/CGPDFObject.h> PDF實例化
#include <CoreGraphics/CGPDFOperatorTable.h> 為PDF操作符存儲回調(diào)函數(shù)的類型践磅。
#include <CoreGraphics/CGPDFPage.h> 一種表示PDF文檔中的頁面的類型。
#include <CoreGraphics/CGPDFScanner.h> 解析PDF掃描對象的內(nèi)容流灸异。
#include <CoreGraphics/CGPDFStream.h> 表示PDF流的類型府适。
#include <CoreGraphics/CGPDFString.h> 表示PDF文檔中的字符串的數(shù)據(jù)類型。
#include <CoreGraphics/CGPath.h> 核心圖形的路徑肺樟。
#include <CoreGraphics/CGPattern.h> 用于繪制圖形路徑的2D模式檐春。
#include <CoreGraphics/CGShading.h> 由您提供的自定義函數(shù)控制的顏色平滑過渡的定義,用于繪制徑向和軸向漸變填充么伯。
以上類的解釋大部分詩官方文檔直譯疟暖,翻譯的有些拗口
來到/CGContext.h中,常用的函數(shù)如下:
返回CFTypeID
CFTypeID CGContextGetTypeID(void)
將當(dāng)前圖形狀態(tài)推入堆棧。之后俐巴,您對圖形狀態(tài)所做的修改會影響隨后的的描畫操作骨望,但不影響存儲在棧堆中的拷貝。
CGContextSaveGState(CGContextRef cg_nullable c)
把棧堆頂部狀態(tài)彈出欣舵,返回之前的圖形狀態(tài)擎鸠。
CGContextRestoreGState(CGContextRef cg_nullable c)
分別在X軸方向縮放sx,在Y軸方向縮放sy
CGContextScaleCTM(CGContextRef cg_nullable c,CGFloat sx, CGFloat sy)
分別在X軸方向移動tx邻遏,在Y軸方向移動ty
CGContextTranslateCTM(CGContextRef cg_nullable c,CGFloat tx, CGFloat ty)
旋轉(zhuǎn)角度 angle
CGContextRotateCTM(CGContextRef cg_nullable c, CGFloat angle)
使用 transform 變換矩陣對 CGContextRef 的坐標(biāo)系統(tǒng)執(zhí)行變換
CGContextConcatCTM(CGContextRef cg_nullable c,CGAffineTransform transform)
獲取CGContextRef的坐標(biāo)系統(tǒng)的變換矩陣糠亩。
CGAffineTransform CGContextGetCTM(CGContextRef cg_nullable c)
設(shè)置繪圖的線寬
CGContextSetLineWidth(CGContextRef cg_nullable c, CGFloat width)
設(shè)置線的端點的樣式
CGContextSetLineCap(CGContextRef cg_nullable c, CGLineCap cap)
設(shè)置接接線的樣式
CGContextSetLineJoin(CGContextRef cg_nullable c, CGLineJoin join)
設(shè)置圖像上下文中的連接線的斜接限制。
CGContextSetMiterLimit(CGContextRef cg_nullable c, CGFloat limit)
設(shè)置圖形上下文中的虛線的模式准验。
CGContextSetLineDash(CGContextRef cg_nullable c, CGFloat phase,
const CGFloat * __nullable lengths, size_t count)
設(shè)置彎曲的路徑中的圖形上下文的準(zhǔn)確性
CGContextSetFlatness(CGContextRef cg_nullable c, CGFloat flatness)
設(shè)置圖形上下文的透明度
CGContextSetAlpha(CGContextRef cg_nullable c, CGFloat alpha)
設(shè)置回合模式
CGContextSetBlendMode(CGContextRef cg_nullable c, CGBlendMode mode)
開始一個新的路徑,舊的路徑被丟棄
CGContextBeginPath(CGContextRef cg_nullable c)
在一個新的點開始新的路徑
CGContextMoveToPoint(CGContextRef cg_nullable c,CGFloat x, CGFloat y)
從當(dāng)前點到指定點添加一條線
CGContextAddLineToPoint(CGContextRef cg_nullable c,
CGFloat x, CGFloat y)
從當(dāng)前點到指定點添加第一條曲線
CGContextAddCurveToPoint(CGContextRef cg_nullable c, CGFloat cp1x,
CGFloat cp1y, CGFloat cp2x, CGFloat cp2y, CGFloat x, CGFloat y)
貝塞爾曲線
CGContextAddQuadCurveToPoint(CGContextRef cg_nullable c,
CGFloat cpx, CGFloat cpy, CGFloat x, CGFloat y)
閉合路徑
CGContextClosePath(CGContextRef cg_nullable c)
矩形
CGContextAddRect(CGContextRef cg_nullable c, CGRect rect)
多個矩形
CGContextAddRects(CGContextRef cg_nullable c,
const CGRect * __nullable rects, size_t count)
多條線
CGContextAddLines(CGContextRef cg_nullable c,
const CGPoint * __nullable points, size_t count)
畫橢圓
CGContextAddEllipseInRect(CGContextRef cg_nullable c, CGRect rect)
圓廷没,扇形
CGContextAddArc(CGContextRef cg_nullable c, CGFloat x, CGFloat y,
CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwi)
畫圓弧
CGContextAddArcToPoint(CGContextRef cg_nullable c,
CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2, CGFloat radius)
添加路徑
CGContextAddPath(CGContextRef cg_nullable c,
CGPathRef cg_nullable path)
將路徑替換為線路徑
CGContextReplacePathWithStrokedPath(CGContextRef cg_nullable c)
判斷路徑是否為空
bool CGContextIsPathEmpty(CGContextRef cg_nullable c)
獲取路徑當(dāng)前的點
CGPoint CGContextGetPathCurrentPoint(CGContextRef cg_nullable c)
返回路徑的邊界框
CGRect CGContextGetPathBoundingBox(CGContextRef cg_nullable c)
拷貝路徑
CGPathRef __nullable CGContextCopyPath(CGContextRef cg_nullable c)
點是否包含在路徑中
bool CGContextPathContainsPoint(CGContextRef cg_nullable c,
CGPoint point, CGPathDrawingMode mode)
繪制路徑
CGContextDrawPath(CGContextRef cg_nullable c,
CGPathDrawingMode mode)
填充路徑
CGContextFillPath(CGContextRef cg_nullable c)
奇偶填充路徑
CGContextEOFillPath(CGContextRef cg_nullable c)
給路徑畫線
CGContextStrokePath(CGContextRef cg_nullable c)
填充矩形
CGContextFillRect(CGContextRef cg_nullable c, CGRect rect)
填充矩形組
CGContextFillRects(CGContextRef cg_nullable c,
const CGRect * __nullable rects, size_t count)
矩形畫線
CGContextStrokeRect(CGContextRef cg_nullable c, CGRect rect)
矩形畫線并設(shè)置線寬
CGContextStrokeRectWithWidth(CGContextRef cg_nullable c,
CGRect rect, CGFloat width)
清除矩形
CGContextClearRect(CGContextRef cg_nullable c, CGRect rect)
填充矩形內(nèi)的橢圓
CGContextFillEllipseInRect(CGContextRef cg_nullable c,
CGRect rect)
矩形內(nèi)部橢圓畫線
CGContextStrokeEllipseInRect(CGContextRef cg_nullable c,
CGRect rect)
線段糊饱,點的數(shù)組
CGContextStrokeLineSegments(CGContextRef cg_nullable c,
const CGPoint * __nullable points, size_t count)
根據(jù)圖形上下文獲取剪輯路徑
CGContextClip(CGContextRef cg_nullable c)
使用奇偶填充規(guī)則決定剪輯路徑
CGContextEOClip(CGContextRef cg_nullable c)
CGContextResetClip(CGContextRef c)
CGContextClipToMask(CGContextRef cg_nullable c, CGRect rect,
CGImageRef cg_nullable mask)
CGRect CGContextGetClipBoundingBox(CGContextRef cg_nullable c)
CGContextClipToRect(CGContextRef cg_nullable c, CGRect rect)
CGContextClipToRects(CGContextRef cg_nullable c,
const CGRect * rects, size_t count)
CGContextSetFillColorWithColor(CGContextRef cg_nullable c,
CGColorRef cg_nullable color)
CGContextSetStrokeColorWithColor(CGContextRef cg_nullable c,
CGColorRef cg_nullable color)
CGContextSetFillColorSpace(CGContextRef cg_nullable c,
CGColorSpaceRef cg_nullable space)
CGContextSetStrokeColorSpace(CGContextRef cg_nullable c,
CGColorSpaceRef cg_nullable space)
CGContextSetFillColor(CGContextRef cg_nullable c,
const CGFloat * cg_nullable components)
CGContextSetStrokeColor(CGContextRef cg_nullable c,
const CGFloat * cg_nullable components)
CGContextSetFillPattern(CGContextRef cg_nullable c,
CGPatternRef cg_nullable pattern, const CGFloat * cg_nullable components)
CGContextSetStrokePattern(CGContextRef cg_nullable c,
CGPatternRef cg_nullable pattern, const CGFloat * cg_nullable components)
CGContextSetPatternPhase(CGContextRef cg_nullable c, CGSize phase)
CGContextSetGrayFillColor(CGContextRef cg_nullable c,
CGFloat gray, CGFloat alpha)
CGContextSetGrayStrokeColor(CGContextRef cg_nullable c,
CGFloat gray, CGFloat alpha)
CGContextSetRGBFillColor(CGContextRef cg_nullable c, CGFloat red,
CGFloat green, CGFloat blue, CGFloat alpha)
CGContextSetRGBStrokeColor(CGContextRef cg_nullable c,
CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)
CGContextSetCMYKFillColor(CGContextRef cg_nullable c,
CGFloat cyan, CGFloat magenta, CGFloat yellow, CGFloat black, CGFloat alpha)
CGContextSetCMYKStrokeColor(CGContextRef cg_nullable c,
CGFloat cyan, CGFloat magenta, CGFloat yellow, CGFloat black, CGFloat alpha)
CGContextSetRenderingIntent(CGContextRef cg_nullable c,
CGColorRenderingIntent intent)
CGContextDrawImage(CGContextRef cg_nullable c, CGRect rect,
CGImageRef cg_nullable image)
CGContextDrawTiledImage(CGContextRef cg_nullable c, CGRect rect,
CGImageRef cg_nullable image)
CGInterpolationQuality CGContextGetInterpolationQuality(CGContextRef cg_nullable c)
CGContextSetInterpolationQuality(CGContextRef cg_nullable c,
CGInterpolationQuality quality)
CGContextSetShadowWithColor(CGContextRef cg_nullable c,
CGSize offset, CGFloat blur, CGColorRef __nullable color)
CGContextSetShadow(CGContextRef cg_nullable c, CGSize offset,
CGFloat blur)
CGContextDrawLinearGradient(CGContextRef cg_nullable c,
CGGradientRef cg_nullable gradient, CGPoint startPoint, CGPoint endPoint,
CGGradientDrawingOptions options)
CGContextDrawRadialGradient(CGContextRef cg_nullable c,
CGGradientRef cg_nullable gradient, CGPoint startCenter, CGFloat startRadius,
CGPoint endCenter, CGFloat endRadius, CGGradientDrawingOptions options)
CGContextDrawShading(CGContextRef cg_nullable c,
cg_nullable CGShadingRef shading)
CGContextSetCharacterSpacing(CGContextRef cg_nullable c,
CGFloat spacing)
CGContextSetTextPosition(CGContextRef cg_nullable c,
CGFloat x, CGFloat y)
CGPoint CGContextGetTextPosition(CGContextRef cg_nullable c)
CGContextSetTextMatrix(CGContextRef cg_nullable c,
CGAffineTransform t)
CGAffineTransform CGContextGetTextMatrix(CGContextRef cg_nullable c)
CGContextSetTextDrawingMode(CGContextRef cg_nullable c,
CGTextDrawingMode mode)
CGContextSetFont(CGContextRef cg_nullable c,
CGFontRef cg_nullable font)
CGContextSetFontSize(CGContextRef cg_nullable c, CGFloat size)
CGContextShowGlyphsAtPositions(CGContextRef cg_nullable c,
const CGGlyph * cg_nullable glyphs, const CGPoint * cg_nullable Lpositions,
size_t count)
CGContextDrawPDFPage(CGContextRef cg_nullable c,
CGPDFPageRef cg_nullable page)
CGContextBeginPage(CGContextRef cg_nullable c,
const CGRect * __nullable mediaBox)
CGContextEndPage(CGContextRef cg_nullable c)
CGContextRef cg_nullable CGContextRetain(CGContextRef cg_nullable c)
CGContextRelease(CGContextRef cg_nullable c)
CGContextFlush(CGContextRef cg_nullable c)
CGContextSynchronize(CGContextRef cg_nullable c)
CGContextSetShouldAntialias(CGContextRef cg_nullable c,
bool shouldAntialias)
CGContextSetAllowsAntialiasing(CGContextRef cg_nullable c,
bool allowsAntialiasing)
CGContextSetShouldSmoothFonts(CGContextRef cg_nullable c,
bool shouldSmoothFonts)
CGContextSetAllowsFontSmoothing(CGContextRef cg_nullable c,
bool allowsFontSmoothing)
CGContextSetShouldSubpixelPositionFonts(
CGContextRef cg_nullable c, bool shouldSubpixelPositionFonts)
CGContextSetAllowsFontSubpixelPositioning(
CGContextRef cg_nullable c, bool allowsFontSubpixelPositioning)
CGContextSetShouldSubpixelQuantizeFonts(
CGContextRef cg_nullable c, bool shouldSubpixelQuantizeFonts)
CGContextSetAllowsFontSubpixelQuantization(
CGContextRef cg_nullable c, bool allowsFontSubpixelQuantization)
CGContextBeginTransparencyLayer(CGContextRef cg_nullable c,
CFDictionaryRef __nullable auxiliaryInfo)
CGContextBeginTransparencyLayerWithRect(
CGContextRef cg_nullable c, CGRect rect, CFDictionaryRef __nullable auxInfo)
CGContextEndTransparencyLayer(CGContextRef cg_nullable c)
CGAffineTransform CGContextGetUserSpaceToDeviceSpaceTransform(CGContextRef cg_nullable c)
CGPoint CGContextConvertPointToDeviceSpace(CGContextRef cg_nullable c,
CGPoint point)
CGPoint CGContextConvertPointToUserSpace(CGContextRef cg_nullable c,
CGPoint point)
CGSize CGContextConvertSizeToDeviceSpace(CGContextRef cg_nullable c,
CGSize size)
CGSize CGContextConvertSizeToUserSpace(CGContextRef cg_nullable c,
CGSize size)
CGRect CGContextConvertRectToDeviceSpace(CGContextRef cg_nullable c,
CGRect rect)
CGRect CGContextConvertRectToUserSpace(CGContextRef cg_nullable c,
CGRect rect)
CGContextSelectFont(CGContextRef cg_nullable c,
const char * cg_nullable name, CGFloat size, CGTextEncoding textEncoding)
CGContextShowText(CGContextRef cg_nullable c,
const char * cg_nullable string, size_t length)
CGContextShowTextAtPoint(CGContextRef cg_nullable c,
CGFloat x, CGFloat y, const char * cg_nullable string, size_t length)
CGContextShowGlyphs(CGContextRef cg_nullable c,
const CGGlyph * __nullable g, size_t count)
CGContextShowGlyphsAtPoint(CGContextRef cg_nullable c, CGFloat x,
CGFloat y, const CGGlyph * __nullable glyphs, size_t count)
CGContextShowGlyphsWithAdvances(CGContextRef cg_nullable c,
const CGGlyph * __nullable glyphs, const CGSize * __nullable advances,
size_t count)
CGContextDrawPDFDocument(CGContextRef cg_nullable c, CGRect rect,
CGPDFDocumentRef cg_nullable document, int page)
簡單演示
-
首先看一下代碼展示效果
tableView截圖
- 簡單介紹一下實現(xiàn)思路:
(1)每一種繪圖方式放在一個cell中,直接在cell內(nèi)部drawRect方法中實現(xiàn)繪圖代碼颠黎;
(2)tableView的一個cell的數(shù)據(jù)通過block方式外面?zhèn)魅肓矸妫簿褪钦f在外面實現(xiàn)block,在cell的drawRect方法中回調(diào)block狭归;
(3)MVVC模式將tableView的數(shù)據(jù)block數(shù)組放在viewModel中處理直接返回數(shù)據(jù)數(shù)組夭坪;
(4)實現(xiàn)每一種繪圖代碼block;
- Cell.h
@interface DrawTableViewCell : UITableViewCell
@property (copy, nonatomic) void (^block)(UITableViewCell *cell);
+ (instancetype)cellWithTableView:(UITableView *)tableView;
@end
- Cell.m
#import "DrawTableViewCell.h"
@implementation DrawTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.backgroundColor = [UIColor whiteColor];
self.selectionStyle = UITableViewCellSelectionStyleNone;
//創(chuàng)建cell的子控件
}
return self;
}
- (void)drawRect:(CGRect)rect{
if (self.block) {
self.block(self);
}
}
#pragma mark - 快速創(chuàng)建Cell
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
static NSString *ID = @"DrawTableViewCell";
DrawTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[DrawTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
}
return cell;
}
- (void)setBlock:(void (^)(UITableViewCell *))block{
_block = block;
[self setNeedsDisplay];
}
@end
- ViewController
#import "ViewController.h"
#import "ViewModel.h"
#import "DrawTableViewCell.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView *mainTableView;
@property (strong, nonatomic) NSArray *dataArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dataArr = [[ViewModel new] tableViewDatas];
[self.view addSubview:self.mainTableView];
// [self saveViewImageToAlbum];
}
//將tableView截圖保存到相冊
- (void)saveViewImageToAlbum{
CGRect oldFrame = self.mainTableView.frame;
self.mainTableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1600);
UIGraphicsBeginImageContextWithOptions(self.mainTableView.frame.size, self.mainTableView.opaque, 1);
[self.mainTableView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
self.mainTableView.frame = oldFrame;
}
#pragma mark --------UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
DrawTableViewCell *cell = [DrawTableViewCell cellWithTableView:tableView];
cell.block = self.dataArr[indexPath.row];
return cell;
}
#pragma mark --------懶加載
- (UITableView *)mainTableView{
if (!_mainTableView) {
_mainTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
_mainTableView.delegate = self;
_mainTableView.dataSource = self;
// _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return _mainTableView;
}
- (NSArray *)dataArr{
if (!_dataArr) {
_dataArr = [NSArray array];
}
return _dataArr;
}
@end
- 重點下面ViewModel繪圖代碼block實現(xiàn)
ViewModel.h
#import <Foundation/Foundation.h>
@interface ViewModel : NSObject
+ (NSArray *)tableViewDatas;
@end
ViewModel.m
#import <UIKit/UIKit.h>
#import "ViewModel.h"
#import <QuartzCore/QuartzCore.h>
@implementation ViewModel
+ (NSArray *)tableViewDatas{
NSMutableArray *arr = [NSMutableArray array];
#pragma ======================================================= 畫圓
void (^drawArc)(UITableViewCell *cell) = ^(UITableViewCell *cell){//畫圓
/**
===============================>>繪制文字 drawInRect
*/
[self drawText:@"畫圓"];
/**
首先介紹一個枚舉值
kCGPathFill, 填充非零繞數(shù)規(guī)則
kCGPathEOFill, 表示奇偶規(guī)則
kCGPathStroke, 路徑
kCGPathFillStroke, 路勁填充
kCGPathEOFillStroke 表示描線过椎,不是填充
這個值可以區(qū)分畫一個邊框(未填充)和填充以及填充類型的圖形室梅。
*/
/**
===============================>>畫一個邊框圓 kCGPathStroke
*/
//第一步:拿到畫板
CGContextRef context = UIGraphicsGetCurrentContext();
//第二步:context 設(shè)置線(邊框)的顏色 如果需要改變顏色就要設(shè)置,如果不設(shè)置疚宇,使用上次設(shè)置的顏色亡鼠,在同一個View中 UIGraphicsGetCurrentContext()函數(shù)每次獲取的 context都是同一個
CGContextSetRGBStrokeColor(context, 0, 0, 1, 1.0);
//第三步:設(shè)置線(邊框)寬
CGContextSetLineWidth(context, 1.0);
//第四步:在畫板上添加一個圓 AddArc
/**
(1).context
(2).x y 為圓點原點
(3).radius 半徑
(4).startAngle 開始角度
(5).endAngle 結(jié)束角度
(6).clockwise 0 為順時針 1 為逆時針
*/
CGContextAddArc(context, 80, 50, 25, 0, 2 * M_PI, 0);
//第五步:開始畫(繪制)kCGPathStroke 畫線、不填充
CGContextDrawPath(context, kCGPathStroke);
/**
kCGLineCapButt,
kCGLineCapRound,
kCGLineCapSquare
*/
/**
================================>>畫一個填充圓
*/
//第二步:設(shè)置填充顏色
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
//第四步:在畫板上添加圓
CGContextAddArc(context, 160, 50, 25, 0, 2 * M_PI, 0);
//第五步:畫圓敷待,kCGPathFill 填充
CGContextDrawPath(context, kCGPathFill);
/**
===============================>>畫一個帶邊框的填充圓
*/
//第二步:設(shè)置線顏色和填充顏色
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
//第三步:設(shè)置線寬
CGContextSetLineWidth(context, 3.0);
//第四步:在畫板上添加圓
CGContextAddArc(context, 240, 50, 25, 0, 2 * M_PI, 0);
//第五步:繪制 kCGPathFillStroke 邊框加填充
CGContextDrawPath(context, kCGPathFillStroke);
/**
================================>>畫一段文字 換行也會識別
*/
NSString *str = @"kCGPathFill,\nkCGPathEOFill,\nkCGPathStroke,\nkCGPathStroke,\nkCGPathFillStroke,\nkCGPathEOFillStroke";
[str drawInRect:CGRectMake(15, 120, 300, 80) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
NSString *text = @"填充非零繞數(shù)規(guī)則\n表示奇偶規(guī)則\n路徑\n路勁填充\n表示描線间涵,不是填充";
[text drawInRect:CGRectMake(150, 120, 300, 80) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
};
[arr addObject:drawArc];
#pragma ======================================================= 畫線
void (^drawLine)(UITableViewCell *cell) = ^(UITableViewCell *cell){//畫線
/**
===============================>>繪制文字
*/
[self drawText:@"畫線和弧線"];
/**
===============================>>畫線
*/
//第一步:拿到畫板
CGContextRef context = UIGraphicsGetCurrentContext();
//第二步:準(zhǔn)備畫線的點
CGPoint aPoints[2];//坐標(biāo)點數(shù)組
aPoints[0] = CGPointMake(100, 30);//坐標(biāo)1
aPoints[1] = CGPointMake(200, 30);//坐標(biāo)2
//第三步:設(shè)置線的顏色
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
//第四步:在畫板上添加一條線
/**
1.context
2.points 坐標(biāo)點數(shù)組
3.cout 大小
*/
CGContextAddLines(context, aPoints, 2);//添加線
//第五步:繪制
CGContextDrawPath(context, kCGPathStroke);//繪制路徑
/**
=================================>>畫笑臉弧線
*/
//左邊
CGContextSetRGBStrokeColor(context, 0, 1, 0.5, 1.0);
CGContextMoveToPoint(context, 220, 25);//開始坐標(biāo)p1
/**
1.context
2.x1,y1跟p1形成一條線的坐標(biāo)p2,x2,y2結(jié)束坐標(biāo)跟p3形成一條線的p3,
3.radius半徑,注意, 需要算好半徑的長度,
*/
CGContextAddArcToPoint(context, 228, 13, 236, 25, 10);
CGContextDrawPath(context, kCGPathStroke);
//右邊
CGContextMoveToPoint(context, 240, 25);//開始坐標(biāo)p1
CGContextAddArcToPoint(context, 248, 13, 256, 25, 10);
CGContextStrokePath(context);
//下邊
CGContextMoveToPoint(context, 230, 35);//開始坐標(biāo)p1
CGContextAddArcToPoint(context, 238, 42, 246, 35, 10);
CGContextStrokePath(context);
/**
===============================>>繪制文字
*/
NSString *text = @"畫圓弧需注意:\n1.context\n2.x1,y1跟p1形成一條線的坐標(biāo)p2榜揖,x2,y2結(jié)束坐標(biāo)跟p3形成一條線的p3,\n3.radius半徑,注意, 需要算好半徑的長度,";
[text drawInRect:CGRectMake(15, 80, 300, 120) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
};
[arr addObject:drawLine];
#pragma ======================================================= 繪制矩形以及漸變色填充
void (^drawRec)(UITableViewCell *cell) = ^(UITableViewCell *cell){//矩形
/**
===============================>>繪制文字
*/
[self drawText:@"畫矩形"];
/**
================================>>畫一個矩形
*/
CGContextRef context = UIGraphicsGetCurrentContext();
//畫方框
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
CGContextStrokeRect(context, CGRectMake(60, 10, 50, 50));
/**
================================>>畫一個填充矩形
*/
CGContextSetFillColorWithColor(context, [UIColor cyanColor].CGColor);
CGContextFillRect(context, CGRectMake(120, 10, 50, 50));
/**
================================>>畫一個漸變色填充矩形
*/
/**接下來介紹幾種填充漸變色的方式 第一種 是在 QuartzCore 框架下得實現(xiàn)方式勾哩,第二種才是 CoreGraphics方式,雖然都能實現(xiàn)漸變色举哟,但是兩種截然不同的東西*/
/**
第一種填充方式必須導(dǎo)入quartcore #import <QuartzCore/QuartzCore.h>思劳,這個就不屬于在context上畫,而是將層插入到view層上面炎滞。那么這里就設(shè)計到Quartz Core 圖層編程了敢艰。
*/
CAGradientLayer *gradient1 = [CAGradientLayer layer];
gradient1.frame = CGRectMake(300, 10, 50, 50);
gradient1.colors = @[(id)[UIColor whiteColor].CGColor,
(id)[UIColor grayColor].CGColor,
(id)[UIColor blackColor].CGColor,
(id)[UIColor yellowColor].CGColor,
(id)[UIColor blueColor].CGColor,
(id)[UIColor redColor].CGColor,
(id)[UIColor greenColor].CGColor,
(id)[UIColor orangeColor].CGColor,
(id)[UIColor brownColor].CGColor];
[cell.layer insertSublayer:gradient1 atIndex:0];
NSLog(@"%@",cell.layer.sublayers);
/**
第二種填充方式 CGGradientRef
*/
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] = {
1,1,1,1.0,
1,1,0,1.0,
1,0,0,1.0,
1,0,1,1.0,
0,1,1,1.0,
0,1,0,1.0,
0,0,1,1.0,
0,0,0,1.0,
};
CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0]) * 4));//形成梯形漸變效果
CGColorSpaceRelease(rgb);
//畫線形成一個矩形
//CGContextSaveGState 與 CGContextRestoreGState 的作用
/**
CGContextSaveGState 函數(shù)的作用是將當(dāng)前圖形狀態(tài)推入堆棧。之后册赛,您對圖形狀態(tài)所做的修改會影響隨后的的描畫操作钠导,但不影響存儲在棧堆中的拷貝震嫉。在修改完成后,您可以通過 CGContextRestoreGState 函數(shù)把棧堆頂部狀態(tài)彈出牡属,返回之前的圖形狀態(tài)票堵。這種推入和彈出的方式是回到之前圖形狀態(tài)的快速方法,避免逐個撤銷所有的狀態(tài)修改逮栅;這也是將某些狀態(tài)(比如裁剪路徑)恢復(fù)到原有設(shè)置的唯一方式悴势。
*/
CGContextSaveGState(context);
CGContextMoveToPoint(context, 190, 10);
CGContextAddLineToPoint(context, 240, 10);
CGContextAddLineToPoint(context, 240, 65);
CGContextAddLineToPoint(context, 190, 65);
CGContextClip(context);//contenxt 裁剪路徑,后續(xù)操作的路徑
CGContextDrawLinearGradient(context, gradient, CGPointMake(190, 10), CGPointMake(190, 65), kCGGradientDrawsAfterEndLocation);
CGContextRestoreGState(context);
/**
下面再看一個顏色漸變的圓
*/
CGContextDrawRadialGradient(context, gradient, CGPointMake(260, 20), 0, CGPointMake(260, 20), 20, kCGGradientDrawsBeforeStartLocation);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
/**
===============================>>繪制文字
*/
[@"CGContextSaveGState 函數(shù)的作用是將當(dāng)前圖形狀態(tài)推入堆棧措伐。之后特纤,您對圖形狀態(tài)所做的修改會影響隨后的的描畫操作,但不影響存儲在棧堆中的拷貝侥加。在修改完成后捧存,您可以通過 CGContextRestoreGState 函數(shù)把棧堆頂部狀態(tài)彈出,返回之前的圖形狀態(tài)担败。這種推入和彈出的方式是回到之前圖形狀態(tài)的快速方法昔穴,避免逐個撤銷所有的狀態(tài)修改;這也是將某些狀態(tài)(比如裁剪路徑)恢復(fù)到原有設(shè)置的唯一方式提前。" drawInRect:CGRectMake(15, 70, [UIScreen mainScreen].bounds.size.width - 30, 140) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
};
[arr addObject:drawRec];
#pragma ======================================================= 繪制橢圓
void (^drawEllipse)(UITableViewCell *cell) = ^(UITableViewCell *cell){//橢圓
/**
===============================>>繪制文字
*/
[self drawText:@"畫扇形和橢圓"];
/**
===============================>>畫一個扇形
*/
CGContextRef context = UIGraphicsGetCurrentContext();
//畫扇形吗货,也就是畫圓,只不過是設(shè)置角度的大小狈网,形成一個扇形
CGContextSetFillColorWithColor(context, [UIColor magentaColor].CGColor);
CGContextMoveToPoint(context, 125, 45);
CGContextAddArc(context, 125, 45, 35, - M_PI_4, - 3 * M_PI_4, 1);
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);//繪制路徑
/**
================================>>畫橢圓
*/
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
CGContextAddEllipseInRect(context, CGRectMake(195, 10, 50, 40));
CGContextDrawPath(context, kCGPathFillStroke);
/**
===============================>>繪制文字
*/
[@"畫扇形其實就是畫圓宙搬,只不過是設(shè)置角度大小形成一個扇形;\n CGContextAddEllipseInRect函數(shù)畫橢圓" drawInRect:CGRectMake(15, 70, [UIScreen mainScreen].bounds.size.width - 30, 140) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
};
[arr addObject:drawEllipse];
#pragma ======================================================= 畫圓角矩形
void (^drawRaAr)(UITableViewCell *cell) = ^(UITableViewCell *cell){
/**
===============================>>繪制文字
*/
[self drawText:@"畫圓角矩形"];
/**
===============================>>畫一個圓角矩形
*/
CGContextRef context = UIGraphicsGetCurrentContext();
float fw = 220;
float fh = 70;
CGContextMoveToPoint(context, fw, fh - 20);//開始坐標(biāo)
CGContextAddArcToPoint(context, fw, fh, fw - 20, fh, 10);//右下角角度
CGContextAddArcToPoint(context, 120, fh, 120, fh - 20, 10);//左下角角度
CGContextAddArcToPoint(context, 120, 20, 120 + 20, 20, 10);//左上角角度
CGContextAddArcToPoint(context, fw, 20, fw, 40, 10);//右上角角度
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
};
[arr addObject:drawRaAr];
#pragma ======================================================= 三角形
void (^drawThree)(UITableViewCell *cell) = ^(UITableViewCell *cell){//三角形
/**
===============================>>繪制文字
*/
[self drawText:@"畫三角形"];
/**
================================畫一個三角形
*/
CGContextRef context = UIGraphicsGetCurrentContext();
/**
畫三角形只需要知道三個點孙援,把三個點連起來
*/
CGPoint points[3];
points[0] = CGPointMake(200, 50);
points[1] = CGPointMake(100, 150);
points[2] = CGPointMake(300, 150);
CGContextSetFillColorWithColor(context, [UIColor cyanColor].CGColor);
CGContextSetLineWidth(context, 3.0);
CGContextAddLines(context, points, 3);//添加線
CGContextClosePath(context);
CGContextDrawPath(context, kCGPathFillStroke);
};
[arr addObject:drawThree];
#pragma ======================================================= 貝塞爾
void (^drawQua)(UITableViewCell *cell) = ^(UITableViewCell *cell){
/**
===============================>>繪制文字
*/
[self drawText:@"畫貝塞爾曲線"];
/**
================================>>二次曲線
*/
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
CGContextMoveToPoint(context, 15, 60);
CGContextAddQuadCurveToPoint(context, 155, 120, 300, 40);//設(shè)置貝塞爾曲線的控制點和終點坐標(biāo)
CGContextStrokePath(context);
/**
===================================三次曲線
*/
CGContextSetStrokeColorWithColor(context, [UIColor yellowColor].CGColor);
CGContextMoveToPoint(context, 15, 150);
CGContextAddCurveToPoint(context, 100, 20, 100, 120, 300, 150);//設(shè)置兩個控制點和終點
CGContextStrokePath(context);
};
[arr addObject:drawQua];
#pragma ======================================================= 圖片
void (^drawImg)(UITableViewCell *cell) = ^(UITableViewCell *cell){//圖片
/**
===============================>>繪制文字
*/
[self drawText:@"圖片"];
/**
=================================繪制五張圖片
*/
CGContextRef context = UIGraphicsGetCurrentContext();
for (int i = 1; i <= 5; i ++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"code0%d",i]];
[image drawInRect:CGRectMake(15 + (i - 1) * 60, 50, 50, 50)];
CGContextDrawImage(context, CGRectMake(15 + (i - 1) * 60, 50, 50, 50), image.CGImage);
}
};
[arr addObject:drawImg];
return arr;
}
+ (void)drawText:(NSString *)str{
[str drawInRect:CGRectMake(15, 30, 90, 20) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor redColor]}];
}
遇到問題
CoreGraphics繪圖在tableView中不會出現(xiàn)復(fù)用問題害淤,而QuartzCore CAGradientLayer 插入layer層會產(chǎn)生復(fù)用問題:
CAGradientLayer 在layer層插入導(dǎo)致復(fù)用的問題能夠知道原因:
打印cell的layer.subLayers
2018-04-16 10:40:03.694991+0800 Graphics[71486:5784058] (
"<CAGradientLayer: 0x100dd91e0>",
"<CALayer: 0x100ac4610>",
"<CALayer: 0x100ac5100>"
)
CAGradientLayer 插入后一直會存在layer層中所以會被復(fù)用;
然而CoreGraphics繪圖操作為什么不會出現(xiàn)復(fù)用問題拓售,一直沒有找到合理的解釋窥摄,后面會接著研究,還希望大神指點一二础淤。