這篇教程主要內容展現如何利用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