我试图在xcode中创建一个绘图方法,以便在UIView中绘制不同的形状。此应用程序的目的是将绘图附加到保存在表格中的行(如果需要,我将发布表格代码,但我不认为这个错误是必要的)。
错误的屏幕截图:
import UIKit
/*
This program is for Xcode 6.3 and Swift 1.2
*/
class CanvasView: UIView {
enum ShapeType: String
{
case Line = "Line"
case Ellipse = "Ellipse"
case Rectangle = "Rectangle"
case FilledEllipse = "Filled Ellipse"
case FilledRectangle = "Filled Rectangle"
case Scribble = "Scribble"
}
var shape: ShapeType = .Line
var color: UIColor = UIColor.blueColor()
var first :CGPoint = CGPointZero
var last :CGPoint = CGPointZero
var points: [CGPoint] = []
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextSetStrokeColorWithColor(context, color.CGColor)
CGContextSetFillColorWithColor(context, color.CGColor)
let rect = CGRect(x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y)
switch shape {
case .Line:
CGContextMoveToPoint(context, first.x, first.y)
CGContextAddLineToPoint(context, last.x, last.y)
CGContextStrokePath(context)
case .Ellipse:
CGContextStrokeEllipseInRect(context, rect)
case .Rectangle:
CGContextStrokeRect(context, rect)
case .FilledEllipse:
CGContextFillEllipseInRect(context, rect)
case .FilledRectangle:
CGContextFillRect(context, rect)
case .Scribble:
CGContextMoveToPoint(context, first.x, first.y)
for p in points {
CGContextAddLineToPoint(context, p.x, p.y)
}
CGContextStrokePath(context)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
first = touch.locationInView(self)
last = first
points.removeAll(keepCapacity: true)
if shape == .Scribble {
points.append(first)
}
setNeedsDisplay()
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
last = touch.locationInView(self)
if shape == .Scribble {
points.append(last)
}
setNeedsDisplay()
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
last = touch.locationInView(self)
if shape == .Scribble {
points.append(last)
}
setNeedsDisplay()
}
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
}
}