ios - 让用户画矩形来选择一个区域

标签 ios iphone swift

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

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

最佳答案

我想通了。我刚刚创建了一个 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
}

关于ios - 让用户画矩形来选择一个区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232985/

相关文章:

iphone - 如何更改 iOS Kif 测试的顺序?

ios - -[__NSCFString countByEnumerateWithState :objects:count:]: unrecognized selector sent to instance

ios - 在具有框架问题的 iOS 中使用 swift 制作自定义 UILabel

iphone - 从 NSDictionary 填充表格 View

ios - facebook ios sso 出现 "safari cannot open page"错误

iphone - 如何在按钮中存储字符串值(不能使用标签。)

iPhone SDK : AVAudioRecorder will not record after calling [AVPlayer play]

ios - 为什么按钮没有点击?

ios - 以编程方式获取 uibutton 的约束

ios - 如何使用 WatchKit 服务证书?