[TOC]
1.上下文(CGContextRef)
//1.上下文(CGContextRef)
Managing Graphics Contexts
CGContextFlush
Forces all pending drawing operations in a window context to be rendered immediately to the destination device.
CGContextGetTypeID
Returns the type identifier for a graphics context.
CGContextRelease
Decrements the retain count of a graphics context.
CGContextRetain
Increments the retain count of a graphics context.
CGContextSynchronize
Marks a window context for update.
Saving and Restoring the Current Graphics State
CGContextSaveGState //保存当前绘图状态
Pushes a copy of the current graphics state onto the graphics state stack for the context.
CGContextRestoreGState //恢复之前保存的绘图状态
Sets the current graphics state to the state most recently saved.
Getting and Setting Graphics State Parameters
CGContextGetInterpolationQuality
Returns the current level of interpolation quality for a graphics context.
CGContextSetFlatness
Sets the accuracy of curved paths in a graphics context.
CGContextSetInterpolationQuality
Sets the level of interpolation quality for a graphics context.
CGContextSetMiterLimit
Sets the miter limit for the joins of connected lines in a graphics context.
CGContextSetPatternPhase
Sets the pattern phase of a context.
CGContextSetFillPattern
Sets the fill pattern in the specified graphics context.
CGContextSetRenderingIntent
Sets the rendering intent in the current graphics state.
CGContextSetShouldAntialias
Sets anti-aliasing on or off for a graphics context.
CGContextSetStrokePattern
Sets the stroke pattern in the specified graphics context.
CGContextSetBlendMode //叠加模式
Sets how sample values are composited by a graphics context.
CGContextSetAllowsAntialiasing
Sets whether or not to allow anti-aliasing for a graphics context.
CGContextSetAllowsFontSmoothing
Sets whether or not to allow font smoothing for a graphics context.
CGContextSetShouldSmoothFonts
Enables or disables font smoothing in a graphics context.
CGContextSetAllowsFontSubpixelPositioning
Sets whether or not to allow subpixel positioning for a graphics context
CGContextSetShouldSubpixelPositionFonts
Enables or disables subpixel positioning in a graphics context.
CGContextSetAllowsFontSubpixelQuantization
Sets whether or not to allow subpixel quantization for a graphics context
CGContextSetShouldSubpixelQuantizeFonts
Enables or disables subpixel quantization in a graphics context.
2.几何路径(Path):
点(Point) 线(Line) 曲线(贝塞尔曲线,Curve) 弧(Arc) 矩形(Rect) 椭圆/圆(Ellipse)
放射矩阵转换(transform)
ClipPath: 剪切路径 复杂绘图都是基于几何路径!!!!
//2.几何路径(Path):
/*
点(Point) 线(Line) 曲线(贝塞尔曲线,Curve) 弧(Arc) 矩形(Rect) 椭圆/圆(Ellipse)
放射矩阵转换(transform)
ClipPath: 剪切路径
复杂绘图都是基于几何路径!!!!
*/
Constructing Paths
//开始路径
CGContextBeginPath
Creates a new empty path in a graphics context.
CGContextClosePath
Closes and terminates the current path’s subpath.
CGContextMoveToPoint 开始位置
Begins a new subpath at the point you specify.
CGContextAddLines 直线
Adds a sequence of connected straight-line segments to the current path.
CGContextAddLineToPoint
Appends a straight line segment from the current point to the provided point .
CGContextAddArc 圆弧
Adds an arc of a circle to the current path, possibly preceded by a straight line segment
CGContextAddArcToPoint
Adds an arc of a circle to the current path, using a radius and tangent points.
CGContextAddCurveToPoint Bézier曲线
Appends a cubic Bézier curve from the current point, using the provided control points and end point .
CGContextAddQuadCurveToPoint
Appends a quadratic Bézier curve from the current point, using a control point and an end point you specify.
CGContextAddRect 矩形
Adds a rectangular path to the current path.
CGContextAddRects
Adds a set of rectangular paths to the current path.
CGContextAddEllipseInRect 圆 & 椭圆
Adds an ellipse that fits inside the specified rectangle.
//矩阵转换
These functions allow you to examine and change the current transformation matrix (CTM) in a graphics context.
CGContextGetCTM //CTM(current transformation matrix)
Returns the current transformation matrix.
CGContextRotateCTM //旋转
Rotates the user coordinate system in a context.
CGContextScaleCTM //缩放
Changes the scale of the user coordinate system in a context.
CGContextTranslateCTM //平移
Changes the origin of the user coordinate system in a context.
CGContextConcatCTM //组合
Transforms the user coordinate system in a context using a specified matrix.
CGContextAddPath 直接复制路径
Adds a previously created path object to the current path in a graphics context.
CGContextCopyPath
Returns a path object built from the current path information in a graphics context.
Getting Information About Paths
CGContextIsPathEmpty
Indicates whether the current path contains any subpaths.
CGContextGetPathCurrentPoint
Returns the current point in a non-empty path.
CGContextGetPathBoundingBox
Returns the smallest rectangle that contains the current path.
CGContextPathContainsPoint
Checks to see whether the specified point is contained in the current path.
Modifying Clipping Paths
CGContextClip //修改当前剪贴路径,使用非零绕数规则。
Modifies the current clipping path, using the nonzero winding number rule.
CGContextEOClip //修改当前剪贴路径,使用奇偶规则
Modifies the current clipping path, using the even-odd rule.
CGContextClipToRect
Sets the clipping path to the intersection of the current clipping path with the area defined by the specified rectangle.
CGContextClipToRects
Sets the clipping path to the intersection of the current clipping path with the region defined by an array of rectangles.
CGContextGetClipBoundingBox
Returns the bounding box of a clipping path.
CGContextClipToMask
Maps a mask into the specified rectangle and intersects it with the current clipping area of the graphics context.
Transforming User Space
3.绘制模式
线型: 线条宽度:Line Width 点线(LineDash): 也就是虚线模式,增加线宽可以实现条形码 端点(LineCap) 连接点( lineJoin)
颜色: 画笔颜色 stroke color 填充颜色 Fill Color
阴影:shadow
叠加模式:BlendMode 默认情况下,后面的绘图会完全覆盖前面的绘图。
绘制方式 轮廓绘制 Stroke 填充绘制 Fill
//3.绘制模式
线型:
线条宽度:Line Width
点线(LineDash): 也就是虚线模式,增加线宽可以实现条形码
端点(LineCap)
连接点( lineJoin)
颜色:
画笔颜色 stroke color
填充颜色 Fill Color
阴影:shadow
叠加模式:BlendMode 默认情况下,后面的绘图会完全覆盖前面的绘图。
绘制方式
轮廓绘制 Stroke
填充绘制 Fill
CGContextSetLineWidth
CGContextSetLineDash
CGContextSetLineDash(<#CGContextRef c#>, <#CGFloat phase#>, <#const CGFloat *lengths#>, <#size_t count#>)
//第一个参数:绘图的上下文
//第二个参数:相位:起始位置,对应数组的元素,可能是空格还是线条
//第三个参数:数组: 线条宽度 间隔宽度;可以多个
//第四个参数:数组的长度
CGContextSetLineCap
Sets the style for the endpoints of lines drawn in a graphics context.
CGContextSetLineJoin
Sets the style for the joins of connected lines in a graphics context.
颜色:
画笔颜色 stroke color
填充颜色 Fill Color
Setting Color, Color Space, and Shadow Values
CGContextSetStrokeColor
Sets the current stroke color.
CGContextSetFillColor
Sets the current fill color.
CGContextSetStrokeColorWithColor
Sets the current stroke color in a context, using a CGColor.
CGContextSetFillColorWithColor
Sets the current fill color in a graphics context, using a CGColor.
CGContextSetRGBStrokeColor
Sets the current stroke color to a value in the DeviceRGB color space.
CGContextSetRGBFillColor
Sets the current fill color to a value in the DeviceRGB color space.
CGContextSetCMYKStrokeColor
Sets the current stroke color to a value in the DeviceCMYK color space.
CGContextSetCMYKFillColor
Sets the current fill color to a value in the DeviceCMYK color space.
CGContextSetGrayStrokeColor
Sets the current stroke color to a value in the DeviceGray color space.
CGContextSetGrayFillColor
Sets the current fill color to a value in the DeviceGray color space.
CGContextSetStrokeColorSpace //色彩空间 //对应类:typedef struct CGColorSpace *CGColorSpaceRef;
Sets the stroke color space in a graphics context.
CGContextSetFillColorSpace
Sets the fill color space in a graphics context.
CGContextSetAlpha //透明度
Sets the opacity level for objects drawn in a graphics context.
//阴影
CGContextSetShadow
Enables shadowing in a graphics context.
CGContextSetShadowWithColor
Enables shadowing with color a graphics context.
//叠加模式
CGContextSetBlendMode //叠加模式
Sets how sample values are composited by a graphics context.
CGContextSetBlendMode(CGContextRef cg_nullable c, CGBlendMode mode)
typedef CF_ENUM (int32_t, CGBlendMode) {
/* Available in Mac OS X 10.4 & later. */
kCGBlendModeNormal,
kCGBlendModeMultiply,
kCGBlendModeScreen,
kCGBlendModeOverlay,
kCGBlendModeDarken,
kCGBlendModeLighten,
kCGBlendModeColorDodge,
kCGBlendModeColorBurn,
kCGBlendModeSoftLight,
kCGBlendModeHardLight,
kCGBlendModeDifference,
kCGBlendModeExclusion,
kCGBlendModeHue,
kCGBlendModeSaturation,
kCGBlendModeColor,
kCGBlendModeLuminosity,
/* Available in Mac OS X 10.5 & later. R, S, and D are, respectively,
premultiplied result, source, and destination colors with alpha; Ra,
Sa, and Da are the alpha components of these colors.
The Porter-Duff "source over" mode is called `kCGBlendModeNormal':
R = S + D*(1 - Sa)
Note that the Porter-Duff "XOR" mode is only titularly related to the
classical bitmap XOR operation (which is unsupported by
CoreGraphics). */
kCGBlendModeClear, /* R = 0 */
kCGBlendModeCopy, /* R = S */
kCGBlendModeSourceIn, /* R = S*Da */
kCGBlendModeSourceOut, /* R = S*(1 - Da) */
kCGBlendModeSourceAtop, /* R = S*Da + D*(1 - Sa) */
kCGBlendModeDestinationOver, /* R = S*(1 - Da) + D */
kCGBlendModeDestinationIn, /* R = D*Sa */
kCGBlendModeDestinationOut, /* R = D*(1 - Sa) */
kCGBlendModeDestinationAtop, /* R = S*(1 - Da) + D*Sa */
kCGBlendModeXOR, /* R = S*(1 - Da) + D*(1 - Sa) */
kCGBlendModePlusDarker, /* R = MAX(0, (1 - D) + (1 - S)) */
kCGBlendModePlusLighter /* R = MIN(1, S + D) */
};
绘制方式
轮廓绘制 Stroke
填充绘制 Fill
CGContextDrawPath //通用方法,根据mode决定
Draws the current path using the provided drawing mode.
CGContextDrawPath(CGContextRef cg_nullable c,CGPathDrawingMode mode)
typedef CF_ENUM (int32_t, CGPathDrawingMode) {
kCGPathFill, //填充
kCGPathEOFill, //奇偶填坑
kCGPathStroke, //轮廓
kCGPathEOFillStroke //奇偶轮廓
kCGPathFillStroke, //填充+轮廓
};
CGContextStrokePath //轮廓
Paints a line along the current path.
CGContextFillPath //填充
Paints the area within the current path, using the nonzero winding number rule.
CGContextEOFillPath //奇偶填坑
Paints the area within the current path, using the even-odd fill rule.
//下面方法:路径+绘制综合方法(基本集合图形)
CGContextStrokeLineSegments
Strokes a sequence of line segments.
CGContextStrokeRect
Paints a rectangular path.
CGContextStrokeRectWithWidth
Paints a rectangular path, using the specified line width.
CGContextFillRect
Paints the area contained within the provided rectangle, using the fill color in the current graphics state.
CGContextFillRects
Paints the areas contained within the provided rectangles, using the fill color in the current graphics state.
CGContextClearRect //透明
Paints a transparent rectangle.
CGContextStrokeEllipseInRect
Strokes an ellipse that fits inside the specified rectangle.
CGContextFillEllipseInRect
Paints the area of the ellipse that fits inside the provided rectangle, using the fill color in the current graphics state.
CGContextReplacePathWithStrokedPath
Replaces the path in the graphics context with the stroked version of the path.
文字绘制
Drawing Text
CGContextSetTextPosition //文本绘制起始位置
Sets the location at which text is drawn.
CGContextSetTextMatrix (CGAffineTransform)
Sets the current text matrix.
CGContextGetTextMatrix
Returns the current text matrix.
CGContextGetTextPosition
Returns the location at which text is drawn.
CGContextSetFont
Sets the platform font in a graphics context.
CGContextSetFontSize
Sets the current font size.
CGContextSetCharacterSpacing (文本的字符间距)
Sets the current character spacing.
CGContextSetTextDrawingMode //绘制模式
Sets the current text drawing mode.
typedef CF_ENUM (int32_t, CGTextDrawingMode) {
kCGTextFill,
kCGTextStroke, //空心文字
kCGTextFillStroke,
kCGTextInvisible,
kCGTextFillClip,
kCGTextStrokeClip,
kCGTextFillStrokeClip,
kCGTextClip
};
//绘制方法
@interface NSString(NSStringDrawing)
- (CGSize)sizeWithAttributes:(nullable NSDictionary<NSString *, id> *)attrs;
- (void)drawAtPoint:(CGPoint)point withAttributes:(nullable NSDictionary<NSString *, id> *)attrs;
- (void)drawInRect:(CGRect)rect withAttributes:(nullable NSDictionary<NSString *, id> *)attrs;
@end
@interface NSAttributedString(NSStringDrawing)
- (CGSize)size;
- (void)drawAtPoint:(CGPoint)point;
- (void)drawInRect:(CGRect)rect;
@end
图片绘制:
在内存中绘图: UIGraphicsBeginImageContext/UIGraphicsEndImageContext
图片重绘: CGContextDrawImage
在内存中绘制图片
- (UIImage*) drawImage
{
//1.调用UIGraphicsBeginImageContext(CGSize size)准备绘图环境
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
//2.调用UIGraphicsGetCurrentContext获取绘图上下文CGContextRef
CGContextRef ctx = UIGraphicsGetCurrentContext();
//3.在CGContextRef中绘图
// ---------下面开始向内存中绘制图形---------
//方法一:直接绘制
// 设置线宽
CGContextSetLineWidth(ctx, 8);
// 设置线条颜色
CGContextSetRGBStrokeColor(ctx, 0 , 1, 0 , 1);
// 绘制一个矩形边框
CGContextStrokeRect(ctx , CGRectMake(30 , 30 , 120 , 60));
// 设置填充颜色
CGContextSetRGBFillColor(ctx, 1, 1, 0 , 1);
// 绘制一个矩形边框
CGContextFillRect(ctx , CGRectMake(180 , 30 , 120 , 60));
// 设置线条颜色
CGContextSetRGBStrokeColor(ctx, 0, 1 , 1 , 1);
// 绘制一个椭圆
CGContextStrokeEllipseInRect(ctx , CGRectMake(30 , 120 , 120 , 60));
// 设置填充颜色
CGContextSetRGBFillColor(ctx, 1, 0 , 1 , 1);
// 填充一个椭圆
CGContextFillEllipseInRect(ctx , CGRectMake(180 , 120 , 120 , 60));
//方法二:将图片绘制到Context中
//CGContextDrawImage(CGContextRef cg_nullable c, CGRect rect,CGImageRef cg_nullable image);
//CGContextDrawTiledImage(CGContextRef cg_nullable c, CGRect rect,CGImageRef cg_nullable image);
//CGContextDrawImage(ctx, CGRectMake(30 , 30 , 120 , 60), image.cgImage);
// ---------结束绘图---------
//4.调用UIGraphicsGetImageFromCurrentImageContext获取Context中的图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//5.调用UIGraphicsEndImageContext(void)关闭绘图环境
UIGraphicsEndImageContext();
return newImage;
}
图片重绘
Drawing an Image to a Graphics Context
CGContextDrawTiledImage
Repeatedly draws an image, scaled to the provided rectangle, to fill the current clip region.
CGContextDrawImage //直接将图片绘制到上下文中
Draws an image into a graphics context.
CGContextDrawImage(CGContextRef cg_nullable c, CGRect rect, CGImageRef cg_nullable image); //比例 fit
CGContextDrawTiledImage(CGContextRef cg_nullable c, CGRect rect,CGImageRef cg_nullable image) //比例 fill 变形填充
颜色渐变
Drawing With a Gradient
CGContextDrawLinearGradient //线性渐变
Paints a gradient fill that varies along the line defined by the provided starting and ending points.
CGContextDrawRadialGradient //圆形渐变
Paints a gradient fill that varies along the area defined by the provided starting and ending circles.
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);
最后一个参数:
typedef CF_OPTIONS (uint32_t, CGGradientDrawingOptions) {
kCGGradientDrawsBeforeStartLocation = (1 << 0),
kCGGradientDrawsAfterEndLocation = (1 << 1)
};
参数2:
typedef struct CGGradient *CGGradientRef;
//初始化API:
CGGradientCreateWithColorComponents(CGColorSpaceRef cg_nullable space, const CGFloat * cg_nullable components,const CGFloat * __nullable locations, size_t count);
//参数1:颜色空间:typedef struct CGColorSpace *CGColorSpaceRef;
CGColorSpaceCreateDeviceGray(void);
CGColorSpaceCreateDeviceRGB(void);
CGColorSpaceCreateDeviceCMYK(void);
//components:颜色数组
//locations: 0~1.0 颜色的位置 NULL表示均匀分布
//count: 颜色的个数
//Demo:
CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[16] = {0.0, 0.0, 1.0, 0.5,
1.0, 1.0, 1.0, 0.8,
1.0, 1.0, 1.0, 0.8,
0.0, 0.0, 1.0, 0.5};
CGFloat locations[4] = {0.0, 0.33, 0.66, 1.0};
//Create the gradient.
CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorSpace, components, locations, 4);
CGPoint start, end;
start = CGPointMake(CGRectGetMidX(theRect), CGRectGetMinY(theRect));
end = CGPointMake(CGRectGetMidX(theRect), CGRectGetMaxY(theRect));
//Draw.
CGContextDrawLinearGradient(context, myGradient, start, end, 0);
其他
Drawing With a Shading
CGContextDrawShading //使用指定的阴影的背景,填充剪切路径。
Fills the clipping path of a context with the specified shading.
Using Transparency Layers //使用透明图层
CGContextBeginTransparencyLayer // 开始一个透明层。
Begins a transparency layer.
CGContextBeginTransparencyLayerWithRect //开始透明度层,它的边界是指定的矩形,其内容是有界的。
Begins a transparency layer whose contents are bounded by the specified rectangle.
CGContextEndTransparencyLayer //结束一个透明层。
Ends a transparency layer.
Drawing Glyphs (雕文)
CGContextShowGlyphsAtPositions //在所提供的位置绘制字形。
Draws glyphs at the provided position.
Drawing PDF Content to a Graphics Context
CGContextDrawPDFPage //绘制一个PDF页面到当前的用户空间
Draws the content of a PDF page into the current graphics context.
Setting Up a Page-Based Graphics Context
CGContextBeginPage //基于页面的图形上下文中开始了新的一页。
Starts a new page in a page-based graphics context.
CGContextEndPage //在基于页面的图形上下文结束当前的页面。
Ends the current page in a page-based graphics context.
Converting Between Device Space and User Space //设备空间和用户空间之间的转换
CGContextGetUserSpaceToDeviceSpaceTransform
Returns an affine transform that maps user space coordinates to device space coordinates.
CGContextConvertPointToDeviceSpace
Returns a point that is transformed from user space coordinates to device space coordinates.
CGContextConvertPointToUserSpace
Returns a point that is transformed from device space coordinates to user space coordinates.
CGContextConvertSizeToDeviceSpace
Returns a size that is transformed from user space coordinates to device space coordinates.
CGContextConvertSizeToUserSpace
Returns a size that is transformed from device space coordinates to user space coordinates
CGContextConvertRectToDeviceSpace
Returns a rectangle that is transformed from user space coordinate to device space coordinates.
CGContextConvertRectToUserSpace
Returns a rectangle that is transformed from device space coordinate to user space coordinates.