通过重写UIView的drawRect方法进行绘制使用,如绘制文本字符、绘制图片、绘制图形等。
在iOS中使用drawRect绘图一般分为以下5个步骤:
1、获取绘图上下文
CGContextRef context = UIGraphicsGetCurrentContext();
2、创建并设置路径
3、将路径添加到上下文
如:线宽、线条颜色、填充颜色等
4、设置上下文状态
CGContextAddLines(context, points, 2);
或线
CGContextAddLineToPoint(context, 10.0, 10.0);
或圆
CGContextAddEllipseInRect(context, CGRectZero);
CGContextAddArc(context, 10.0, 10.0, (60.0 * M_PI / 180.0), (120.0 * M_PI / 180.0), 1);
或弧
CGContextAddArcToPoint(context, 10.0, 200.0, 300.0, 200.0, 100.0);
或二次曲线
CGContextAddQuadCurveToPoint(context, 50.0, 80.0, 200.0, 10.0);
或三次曲线
CGContextAddCurveToPoint(context, 250, 280, 250, 400, 280.0, 300.0);
5、绘制路径
CGContextDrawPath(context, kCGPathFillStroke);
或
CGContextStrokePath(context);
6、释放路径
CGPathRelease(path);
注意事项:
1、设置frame的属性,或调用setNeedsDisplay时才会调用drawRect方法。
2、在绘制过程中
(1)针对实际情况获取图形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
(2)有时候,还需要在获取图形上下文之前,设置开始图形上下文;在使用后,设置关闭图形上下文
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0); // 开始图形上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// coding...
UIGraphicsEndImageContext(); // 关闭上下文
3、
1、绘制文本
- (void)drawRect:(CGRect)rect
{
NSString *text = @"devZhang is an iOS developer.iOS开发者 iOS开发者 iOS开发者 iOS开发者 iOS开发者";
// 文本段落样式
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle alloc] init];
textStyle.lineBreakMode = NSLineBreakByWordWrapping; // 结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")
textStyle.alignment = NSTextAlignmentLeft; //(两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然)
textStyle.lineSpacing = 5; // 字体的行间距
textStyle.firstLineHeadIndent = 5.0; // 首行缩进
textStyle.headIndent = 0.0; // 整体缩进(首行除外)
textStyle.tailIndent = 0.0; //
textStyle.minimumLineHeight = 20.0; // 最低行高
textStyle.maximumLineHeight = 20.0; // 最大行高
textStyle.paragraphSpacing = 15; // 段与段之间的间距
textStyle.paragraphSpacingBefore = 22.0f; // 段首行空白空间/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */
textStyle.baseWritingDirection = NSWritingDirectionLeftToRight; // 从左到右的书写方向(一共➡️三种)
textStyle.lineHeightMultiple = 15; /* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */
textStyle.hyphenationFactor = 1; //连字属性 在iOS,唯一支持的值分别为0和1
// 文本属性
NSMutableDictionary *textAttributes = [[NSMutableDictionary alloc] init];
// NSParagraphStyleAttributeName 段落样式
[textAttributes setValue:textStyle forKey:NSParagraphStyleAttributeName];
// NSFontAttributeName 字体名称和大小
[textAttributes setValue:[UIFont systemFontOfSize:12.0] forKey:NSFontAttributeName];
// NSForegroundColorAttributeNam 颜色
[textAttributes setValue:[UIColor redColor] forKey:NSForegroundColorAttributeName];
// 绘制文字
[text drawInRect:rect withAtt