让用户绘制矩形来选择一个区域
Posted
技术标签:
【中文标题】让用户绘制矩形来选择一个区域【英文标题】:let user to draw rectangle to select an area 【发布时间】:2016-02-05 20:31:30 【问题描述】:我是 Swift 的新手,我试图让用户绘制一个矩形(触摸和拖动)来选择图像的一个区域,就像裁剪时一样,但我不想裁剪我只想知道用户创建的 CGRect。
到目前为止,我有一个 .xib,里面有一个 UIImage 和它的 ViewController。我想在图像上方绘制,但我发现的每个关于绘图的教程都是关于子类化 UIView、覆盖 drawRect 并将其作为 xib 类。
【问题讨论】:
继承 UIView 并覆盖 drawRect 有什么问题? 【参考方案1】:我想通了。我刚刚创建了一个 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
【讨论】:
什么是applyFilterToSelectedArea
?你能把它的代码贴出来吗?以上是关于让用户绘制矩形来选择一个区域的主要内容,如果未能解决你的问题,请参考以下文章