概述
吐槽下IOS下 的圖形繪圖邻奠,代碼冗長笤喳,不得不自己重新封裝方法。整理形成本文碌宴。
繪制線
// 繪制直線
+ (void)toDrawLineFromX:(CGFloat)x1 Y:(CGFloat)y1 toX:(CGFloat)x2 toY:(CGFloat)y2 context:(CGContextRef)con{
CGContextMoveToPoint(con, x1, y1);
CGContextAddLineToPoint(con, x2, y2);
CGContextSetLineWidth(con, 1);
CGContextStrokePath(con);
}
繪制矩形
//繪制矩形 杀狡,fillColor填充色
+ (void)toDrawRect:(CGRect)rectangle color:fillColor context:(CGContextRef)ctx{
//創(chuàng)建路徑并獲取句柄
CGMutablePathRef
path = CGPathCreateMutable();
//將矩形添加到路徑中
CGPathAddRect(path,NULL,
rectangle);
//獲取上下文
//將路徑添加到上下文
CGContextAddPath(ctx,
path);
//設(shè)置矩形填充色
[fillColor setFill];
//矩形邊框顏色
[[UIColor
whiteColor] setStroke];
//邊框?qū)挾? CGContextSetLineWidth(ctx,0);
//繪制
CGContextDrawPath(ctx,
kCGPathFillStroke);
CGPathRelease(path);
}
垂直和居中繪制文字
///繪制文字,rect1指定矩形贰镣,繪制文字在這個(gè)矩形水平和垂直居中
+ (void)toDrawTextWithRect:(CGRect)rect1 str:(NSString*)str1 context:(CGContextRef)context{
if( str1 == nil || context == nil)
return;
CGContextSetLineWidth(context, 1.0);
CGContextSetRGBFillColor (context, 0.01, 0.01, 0.01, 1);
//段落格式
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
textStyle.lineBreakMode = NSLineBreakByWordWrapping;
textStyle.alignment = NSTextAlignmentCenter;//水平居中
//字體
UIFont *font = [UIFont boldSystemFontOfSize:22.0];
//構(gòu)建屬性集合
NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:textStyle};
//獲得size
CGSize strSize = [str1 sizeWithAttributes:attributes];
CGFloat marginTop = (rect1.size.height - strSize.height)/2;
//垂直居中要自己計(jì)算
CGRect r = CGRectMake(rect1.origin.x, rect1.origin.y + marginTop,rect1.size.width, strSize.height);
[str1 drawInRect:r withAttributes:attributes];
}
如何使用
假設(shè)把上面的方法放入到一個(gè)類 DrawUtil 中呜象,我們可以通過 DrawUtil 來調(diào)用方法。
定義: #define drawLine(x1,y1,x2,y2,con) [DrawUtil toDrawLineFromX:x1 Y:y1 toX:x2 toY:y2 context:con]
//獲得上下文
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextClearRect(con, rect);
//畫線碑隆,
drawLine(x,y,x+rectWidth,y,con);
//矩形
[DrawUtil toDrawRect:CGRectMake(x*unitWidth+1, y*unitHeight+1,unitWidth-1, unitHeight-1) color:[UIColor whiteColor] context:con];
//文字
[DrawUtil toDrawTextWithRect:rect1 str:@"你" context:context];