让用户绘制矩形以选择区域

时间:2016-02-05 20:31:31

标签: ios iphone swift

我是Swift的新手,我试图让用户绘制一个矩形(触摸和拖动)来选择图像的一个区域,就像裁剪时一样但是我不想裁剪我只是想知道用户创建的CGRect。

到目前为止,我有一个带有UIImage的.xib及其ViewController。我想在图像上方绘制,但我发现的关于绘图的每个教程都是关于UIView的子类,重写drawRect并将其作为xib类。

1 个答案:

答案 0 :(得分:4)

我明白了。我刚刚创建了一个uiview并根据触摸事件更改了它的框架

let overlay = UIView()
var lastPoint = CGPointZero

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    overlay.layer.borderColor = UIColor.blackColor().CGColor
    overlay.backgroundColor = UIColor.clearColor().colorWithAlphaComponent(0.5)
    overlay.hidden = true
    self.view.addSubview(overlay)

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    //Save original tap Point
    if let touch = touches.first {
        lastPoint = touch.locationInView(self.view)
    }   
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    //Get the current known point and redraw
    if let touch = touches.first {
        let currentPoint = touch.locationInView(view)
        reDrawSelectionArea(lastPoint, toPoint: currentPoint)
    }
}

func reDrawSelectionArea(fromPoint: CGPoint, toPoint: CGPoint) {
    overlay.hidden = false

        //Calculate rect from the original point and last known point
        let rect = CGRectMake(min(fromPoint.x, toPoint.x),
        min(fromPoint.y, toPoint.y),
        fabs(fromPoint.x - toPoint.x),
        fabs(fromPoint.y - toPoint.y));

    overlay.frame = rect
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    overlay.hidden = true

    //User has lift his finger, use the rect
    applyFilterToSelectedArea(overlay.frame)

    overlay.frame = CGRectZero //reset overlay for next tap
}