如何通过拖动UIView的边缘来调整大小

时间:2017-02-26 17:51:48

标签: ios swift uiview resize

我正在制作基于照片的iPhone应用。在具有自定义AVFoundation摄像头的视图内,我创建了一个子视图,用于仅拍摄子视图内部区域的图片。可以将其视为裁剪图像的视图。

通过更改宽度和高度常量来调整视图的大小(我希望保留裁剪视图中其他子视图的大小)。当我从左下角拖动时,一切都很完美,但是当我从其他角落开始拖动时,我得到反向行为(我拖到外面,视图缩小,反之亦然) - 我发现这是由于我得到的事实当我计算从裁剪视图中心的变化时的负值。你能帮我找到能阻止这种行为的正确算法吗?

非常感谢你! :

以下是CropView的自定义类

  

CROP_OPTIONS用于裁剪图像

import UIKit

//CROP OPTIONS
struct CROP_OPTIONS {
    var Height: CGFloat!
    var Width: CGFloat!
    var Center: CGPoint!
}

var  _cropoptions: CROP_OPTIONS!

class CropView: UIView {

    let lineWidth: CGFloat = 1.5
    let strokeColor = giveColor(color: .mainBlue)

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        self.layer.borderColor = strokeColor.cgColor
        self.layer.borderWidth = lineWidth
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.backgroundColor = UIColor.clear

        _cropoptions = CROP_OPTIONS()
        _cropoptions.Center = self.center
        _cropoptions.Width = self.bounds.width
        _cropoptions.Height = self.bounds.height

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    var startPosition: CGPoint?
    var originalHeight: CGFloat = 0
    var originalWidth: CGFloat = 0

    var customViewHeight: NSLayoutConstraint!
    var customViewWidth: NSLayoutConstraint!

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        startPosition = touch?.location(in: self)
        originalHeight = customViewHeight.constant //self.frame.height
        originalWidth = customViewWidth.constant //self.frame.width
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        let endPosition = touch?.location(in: self)

        let differenceY = endPosition!.y - startPosition!.y
        var newHeight: CGFloat = originalHeight + differenceY

        newHeight = (newHeight < 75) ? 75.0 : newHeight
        newHeight = (newHeight > 225) ? 225 : newHeight
        customViewHeight.constant = newHeight

        let differenceX = endPosition!.x - startPosition!.x
        var newWidth: CGFloat = originalWidth + differenceX

        newWidth = (newWidth < 75.0) ? 75.0 : newWidth
        newWidth = (newWidth > 350) ? 350.0 : newWidth
        customViewWidth.constant = newWidth

        _cropoptions.Center = self.center
        _cropoptions.Height = self.frame.height
        _cropoptions.Width = self.frame.width
    }
}

0 个答案:

没有答案