在UITouch事件中画圆圈-iOS8 Swift基础教程

这篇教程主要内容展示如何利用Core Graphics Framework画圆圈,当用户点击屏幕时随机生成不同大小的圆,这篇教程在Xcode6和iOS8下编译通过。

打开Xcode,新建项目选择Single View Application,Product Name填写iOS8SwiftDrawingCirclesTutorial,Organization Name和Organization Identifier根据自己填写,选择Swift语言与iPhone设备。

iOS8SwiftDrawingCirclesTutorial

File->New File->iOS->Source -> CocoTouch Class.选择swift 语言,创建继承于UIViewCirleView类,如下图

CirleView

CircleView中增加如下init 方法:

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方法:

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.

override func viewDidLoad() {
  super.viewDidLoad()
  self.view.backgroundColor = UIColor.lightGrayColor()
}

现在当用户点击屏幕时我们需要创建一个cirecle view,接下来在ViewController.swift中重载touchesBegan:withEvent方法中实现

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)
  }
}
  • 1.circle圆圈设置在用户的点击位置
  • 2.circle高度与宽度随机产生,数值在25-75之间
  • 3.创建circleView并添加至main view中

编译运行项目后,点击屏幕可以看到类似如下效果:

circleView

原文:http://www.ioscreator.com/tutorials/drawing-circles-uitouch-ios8-swift

原文地址:https://www.cnblogs.com/Free-Thinker/p/4946904.html