在Swift中的UIImageView的UIImage中移动UIView

时间:2016-11-10 12:44:06

标签: swift uiview uiimageview uiimage uipangesturerecognizer

我正在尝试在基本图像上移动一个图像。

如果我移动UIView,它会越过UIImageView's图片。

如何限制UIView's移动UIImageView's图像?它应该支持方形和矩形。移动视图不应越过边界。

请指导我。

在屏幕截图中,UIImageView背景颜色为黑色。 移动UIView为白色。白色视图正在穿过其图像[屏幕截图2]。如何限制图像?

代码:

 @IBAction func panAcn(sender: UIPanGestureRecognizer) {

    if sender.state == .Began || sender.state == .Changed {

        let translation = sender.translationInView(self.myImgVw)
        // note: 'view' is optional and need to be unwrapped
        sender.view!.center = CGPointMake(sender.view!.center.x + translation.x, sender.view!.center.y + translation.y)
        sender.setTranslation(CGPointMake(0,0), inView: self.myImgVw)
    }
 }

需要输出:

enter image description here

我的输出

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

 @IBAction func panAcn(sender: UIPanGestureRecognizer) {

    if sender.state == .Began || sender.state == .Changed {

        let translation = sender.translationInView(self.myImgVw)
        // note: 'view' is optional and need to be unwrapped
        guard let view = sender.view else { return }
        var newFrame = view.frame
        newFrame.origin.x = max(self.myImgVw.frame.origin.x, view.frame.origin.x + translation.y)  
        newFrame.origin.y = max(self.myImgVw.frame.origin.y, view.frame.origin.y + translation.y)
        view.frame = newFrame        
    }
 }