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

D-M*_*-Mx 4 iphone ios swift

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

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

D-M*_*-Mx 5

我想到了。我刚刚创建了一个uiview并根据touches事件更改了它的框架

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
}
Run Code Online (Sandbox Code Playgroud)

  • 什么是“applyFilterToSelectedArea”?你能发布它的代码吗? (2认同)