前端之家收集整理的这篇文章主要介绍了
swift 快速奔跑的兔几 本节的内容是:绘画,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当一个应用程序绘制图形时,它首先创建一个用于在其中绘制内容的画布,cocoa称之为图形上下文。
在创建一个图形上下文的时候,会指出上下文的大小。在此画布之外所有的绘画操作都将被忽略,不会出现在画布上。
框架矩形:用于定义视图的大小和位置的矩形。
视图可以包含多个子视图,如果一个视图位于另一个视图内部,那么当超视图移动时,它也会移动。框架矩形是相对于其超视图定义的。而边界矩形则是相对于自己的坐标空间的位置和大小。
尽管边界矩形的尺寸通常与框架矩形相同,但是也并不是必须如此。例如,如果视图被旋转,框架矩形将改变大小和位置,而边界则保持不变。
如下代码为绘制纯色矩形的栗子:
// 绘制图像
class RabbitsView: UIView { override func drawRect(rect: CGRect) { UIColor.grayColor().setFill() let pathNew = UIBezierPath(rect: self.bounds) pathNew.fill() } } let viewRect = CGRect(x: 0,y: 0,width: 100,height: 100) let newVIew = RabbitsView(frame: viewRect)
下面的栗子是圆角矩形的代码:
// 绘制图像
class RabbitsView: UIView { override func drawRect(rect: CGRect) { // 收缩边缘 let pathRect = CGRectInset(self.bounds,1,1) let path = UIBezierPath(roundedRect: pathRect,cornerRadius: 10) //let path = UIBezierPath(rect: self.bounds) path.lineWidth = 4 UIColor.grayColor().setFill() UIColor.blackColor().setStroke() path.fill() path.stroke() } } let viewRect = CGRect(x: 0,height: 100) let newVIew = RabbitsView(frame: viewRect)
下面是创建自定义路径的栗子:
// 绘制图像
class RabbitsView: UIView { override func drawRect(rect: CGRect) { let bezierPathNew = UIBezierPath() let drawingRect = CGRectInset(self.bounds,self.bounds.size.width*0.05,self.bounds.size.height*0.05) let topLeft = CGPointMake(CGRectGetMinX(drawingRect),CGRectGetMaxY(drawingRect)) let topRight = CGPointMake(CGRectGetMaxX(drawingRect),CGRectGetMaxY(drawingRect)) let bottomRight = CGPointMake(CGRectGetMaxX(drawingRect),CGRectGetMinY(drawingRect)) let bottomLeft = CGPointMake(CGRectGetMinX(drawingRect),CGRectGetMinY(drawingRect)) let center1 = CGPointMake(CGRectGetMidX(drawingRect),CGRectGetMidY(drawingRect)) bezierPathNew.moveToPoint(topLeft) bezierPathNew.addLineToPoint(topRight) bezierPathNew.addLineToPoint(bottomLeft) bezierPathNew.addCurveToPoint(bottomRight,controlPoint1: center1,controlPoint2: center1) bezierPathNew.closePath() UIColor.grayColor().setFill() UIColor.magentaColor().setStroke() bezierPathNew.fill() bezierPathNew.stroke() } } let viewRect = CGRect(x: 0,height: 100) let newVIew = RabbitsView(frame: viewRect)
绘制多条子路径的栗子如下:
// 绘制图像
class RabbitsView: UIView { override func drawRect(rect: CGRect) { let bezierPathNew = UIBezierPath() let drawingRect = CGRectInset(self.bounds,controlPoint2: center1) bezierPathNew.closePath() let circleRect = CGRectInset(rect,rect.size.width*0.3,rect.size.height*0.3) let bezierPathSecond = UIBezierPath(ovalInRect: circleRect) let bezierPathF = UIBezierPath() bezierPathNew.appendPath(bezierPathSecond) bezierPathF.appendPath(bezierPathNew) UIColor.grayColor().setFill() UIColor.magentaColor().setStroke() bezierPathF.fill() bezierPathF.stroke() } } let viewRect = CGRect(x: 0,height: 100) let newVIew = RabbitsView(frame: viewRect)
呼~好多代码啊~~作为一只兔子要去蹦哒一会儿了喔~~~