IOS开发 图形绘制,绘制线条,矩形,和垂直和居中绘制文字

时间:2022-02-08 08:30:37

概述

  吐槽下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{ //创建路径并获取句柄
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]

  //获得上下文

  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];