2
我是Swift中的新手,我試圖讓用戶繪製一個矩形(觸摸並拖動)來選擇圖像的一個區域,就像剪切時一樣,但我不'不想裁剪我只想知道用戶創建的CGRect。讓用戶繪製矩形來選擇區域
到目前爲止,我有一個內部的UIImage和它的ViewController .xib。我想要在圖像上面繪製,但是我發現的關於繪圖的每個教程都是關於UIView的子類,重寫drawRect並將其作爲xib類。
我是Swift中的新手,我試圖讓用戶繪製一個矩形(觸摸並拖動)來選擇圖像的一個區域,就像剪切時一樣,但我不'不想裁剪我只想知道用戶創建的CGRect。讓用戶繪製矩形來選擇區域
到目前爲止,我有一個內部的UIImage和它的ViewController .xib。我想要在圖像上面繪製,但是我發現的關於繪圖的每個教程都是關於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
}
子類化UIView並覆蓋drawRect有什麼問題? –