吐槽下IOS下 的圖形繪圖,代碼冗長,不得不本身從新封裝方法。整理造成本文。app
// 繪製直線 + (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{ //建立路徑並獲取句柄 CGMutablePathRef path = CGPathCreateMutable(); //將矩形添加到路徑中 CGPathAddRect(path,NULL, rectangle); //獲取上下文 //將路徑添加到上下文 CGContextAddPath(ctx, path); //設置矩形填充色 [fillColor setFill]; //矩形邊框顏色 [[UIColor whiteColor] setStroke]; //邊框寬度 CGContextSetLineWidth(ctx,0); //繪製 CGContextDrawPath(ctx, kCGPathFillStroke); CGPathRelease(path); }
///繪製文字,rect1指定矩形,繪製文字在這個矩形水平和垂直居中 + (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]; //構建屬性集合 NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:textStyle}; //得到size CGSize strSize = [str1 sizeWithAttributes:attributes]; CGFloat marginTop = (rect1.size.height - strSize.height)/2; //垂直居中要本身計算 CGRect r = CGRectMake(rect1.origin.x, rect1.origin.y + marginTop,rect1.size.width, strSize.height); [str1 drawInRect:r withAttributes:attributes]; }
假設把上面的方法放入到一個類 DrawUtil 中,咱們能夠經過 DrawUtil 來調用方法。字體
定義: #define drawLine(x1,y1,x2,y2,con) [DrawUtil toDrawLineFromX:x1 Y:y1 toX:x2 toY:y2 context:con]spa
//得到上下文code
CGContextRef con = UIGraphicsGetCurrentContext();blog
CGContextClearRect(con, rect);it
//畫線,io
drawLine(x,y,x+rectWidth,y,con);table
//矩形class
[DrawUtil toDrawRect:CGRectMake(x*unitWidth+1, y*unitHeight+1,unitWidth-1, unitHeight-1) color:[UIColor whiteColor] context:con];方法
//文字
[DrawUtil toDrawTextWithRect:rect1 str:@"你" context:context];