swift画图

来源:互联网 发布:mac百度云下载没反应 编辑:程序博客网 时间:2024/06/05 02:20

今天写写swift的基础画图,菜鸟直接copy就可以啦,都是我自己代码验证过的。

1.首先定义一个继承UIView自的类,复写drawRect(rect:CGRect)方法,在方法里面获取画笔.

let context:CGContextRef = UIGraphicsGetCurrentContext()!;//获取画笔上下文CGContextSetAllowsAntialiasing(context, true)//抗锯齿设置

在使用时直接传入一个CGRect作为参数创建对象,使用addSubview加入你的页面view.


2.画直线

CGContextSetLineWidth(context,0.5)//设置画笔宽度CGContextSetStrokeColorWithColor(context,UIColor(red:204/255, green: 204/255, blue: 204/255, alpha:1).CGColor)//设置画笔颜色CGContextMoveToPoint(context, 0, 0);                  // 直线起点CGContextAddLineToPoint(context, rect.size.width,0);  // 直线终点CGContextStrokePath(context)                          //关闭路径,渲染

3.画三角形

let sPoints = [CGPointMake(0 , 0),CGPointMake(10, 10),CGPointMake(20, 0)];CGContextAddLines(context, sPoints,3);    //添加线CGContextClosePath(context);              //关闭路径CGContextDrawPath(context, CGPathDrawingMode.FillStroke)//根据坐标绘制路径

为什么要把三角形放在直线后呢,因为这样就可以完成一个带箭头的直线啦


4.画图片

画图片这个必须要说下,如果按传统写法:CGContextDrawImage(context, rect, image)来画的画,你会发现图片都是倒立的,哈哈,据说人家的坐标系是y轴向下的

所以如果你和我一样有这种困扰,按如下方式转换一下,就可以啦!

class func drawImage(context:CGContextRef, image:CGImageRef, rect:CGRect){        CGContextSaveGState(context);        CGContextTranslateCTM(context, rect.origin.x, rect.origin.y);        CGContextTranslateCTM(context, 0, rect.size.height);        CGContextScaleCTM(context, 1.0, -1.0);        CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);        CGContextDrawImage(context, rect, image);        CGContextRestoreGState(context); }

5.画字符串

画字符串时候会碰到一个问题,就是居中对齐,脑子有洞的时候,我们会使用drawAtPoint这个方法,计算出字符串的物理长度,然后去计算一个值作为起点,使他能够实现真正的居中对齐。遇到需要分行每行都居中的时候,就傻了。

其实还有一种思路哇,就是给他所有能用的空间,让他自己去居中就好哒

 let font = UIFont.systemFontOfSize(12 *CGFloat(Const.FONTSCANLE)) let color = UIColor.blackColor() let style =NSMutableParagraphStyle() style.alignment =NSTextAlignment.Left (str asNSString).drawInRect(rect1, withAttributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:color,NSParagraphStyleAttributeName:style])

顺便提一下withAttributes,可以用来设置字体颜色,字体大小,以及偏移属性。
1 0