主要代码是:
import UIKit
class FKCustomView: UIView {
//定义两个变量来记录当前触控点的坐标
var curX:Int=100;
var curY:Int=100;
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
//如果程序需要自行绘制该空间的内容,则可通过重写该方法来实现
override func drawRect(rect: CGRect) {
//获取绘图上下文
var ctx=UIGraphicsGetCurrentContext();
if(ctx != nil){
//设置填充的颜色
CGContextSetFillColorWithColor(ctx, UIColor.redColor().CGColor);
//以触控点为圆心 绘制一个圆形
CGContextFillEllipseInRect(ctx, CGRectMake(CGFloat(curX-10), CGFloat(curY-10), CGFloat(20), CGFloat(20)));
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
//获取触控事件UITouch事件
var touch=touches.first as? UITouch
if(touch != nil){
//得到触碰事件在当前组建上的触碰点
var lastTouch = touch!.locationInView(self)
//获取触碰点的坐标
curX=Int(lastTouch.x);
curY=Int(lastTouch.y);
//通知该组建重绘
self.setNeedsDisplay();
}
}
}