这篇教程主要内容展现如何利用Core Graphics Framework画圆圈,当用户点击屏幕时随机生成不一样大小的圆,这篇教程在Xcode6和iOS8下编译经过。ios
打开Xcode,新建项目选择Single View Application,Product Name填写iOS8SwiftDrawingCirclesTutorial,Organization Name和Organization Identifier根据本身填写,选择Swift语言与iPhone设备。swift
File->New File->iOS->Source -> CocoTouch Class.选择swift 语言,建立继承于UIView
的CirleView
类,以下图dom
在CircleView
中增长以下init 方法:ide
override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
将cirecle view的背景颜色清除掉,这样多个圆圈能够相互重叠在一块儿,下面实现drawRect方法:oop
override func drawRect(rect: CGRect) { // Get the Graphics Context var context = UIGraphicsGetCurrentContext(); // Set the circle outerline-width CGContextSetLineWidth(context, 5.0); // Set the circle outerline-colour UIColor.redColor().set() // Create Circle CGContextAddArc(context, (frame.size.width)/2, frame.size.height/2, (frame.size.width - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1) // Draw CGContextStrokePath(context); }
在drawRect
方法中,咱们将圆圈的边框线设置为5并居中显示,最后调用CGContextStrokePath
画出圆圈.如今咱们打开ViewController.swift文件,在viewDidLoad
方法中将背景颜色设置为ligthgray.ui
override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.lightGrayColor() }
如今当用户点击屏幕时咱们须要建立一个cirecle view,接下来在ViewController.swift中重载touchesBegan:withEvent方法中实现spa
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { // loop through the touches for touch in touches { // Set the Center of the Circle // 1 var circleCenter = touch.locationInView(view) // Set a random Circle Radius // 2 var circleWidth = CGFloat(25 + (arc4random() % 50)) var circleHeight = circleWidth // Create a new CircleView // 3 var circleView = CircleView(frame: CGRectMake(circleCenter.x, circleCenter.y, circleWidth, circleHeight)) view.addSubview(circleView) } }
编译运行项目后,点击屏幕能够看到相似以下效果:3d
原文:http://www.ioscreator.com/tutorials/drawing-circles-uitouch-ios8-swiftcode