как масштабировать вид изображения, изолируя край и растягивая ширину / высоту - PullRequest
0 голосов
/ 08 ноября 2019

Мой код ниже может изменить размер изображения. Он изменяет размер изображения, если я удерживаю его, и перетаскиваю его вниз, но это неустойчиво. Я хочу иметь больше контроля, выбирая край и влияя на высоту этой стороны. Вы можете просто скопировать и вставить код, потому что я не использую раскадровки.

import UIKit
class ViewController: UIViewController {
var james = UIImageView()



    var center: CGPoint! //center of the CS
    let maxSize: CGSize = CGSize.init(width: 300, height: 300) // maximum size of our scaling view
    var maxLengthToCenter: CGFloat! //maximum distance from the center of the CS to the furthest point in the CS

    private func prepareForScaling() {
        self.center = self.view.center //we set the center of our CS to equal the center of the VC's view
        let frame = self.view.frame
        //the furthest distance in the CS is the diagonal, and we calculate it using pythagoras theorem
        self.maxLengthToCenter = (frame.width*frame.width + frame.height*frame.height).squareRoot()
    }



    private func scaledSize(for location: CGPoint) -> CGSize {
        //calculate location x,y differences from the center
        let xDifference = location.x - self.center.x
        let yDifference = location.y - self.center.y

        let scaleFactor = (xDifference*xDifference + yDifference*yDifference).squareRoot()/maxLengthToCenter
        //create scaled size with maxSize and current scale factor
        let scaledSize = CGSize.init(width: maxSize.width*(1-scaleFactor), height: maxSize.height*(1-scaleFactor))

        return scaledSize
    }


    @objc func panGestureAction(_ sender: UIPanGestureRecognizer) {
        UIView.animateKeyframes(withDuration: 0.1, delay: 0, options: UIView.KeyframeAnimationOptions.calculationModeLinear, animations: {

            let location = sender.location(in: sender.view?.superview)

            sender.view?.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: self.scaledSize(for: location))

            sender.view?.center = location
        })
    }

override func viewDidLoad() {
    super.viewDidLoad()
           self.prepareForScaling()
    // Do any additional setup after loading the view.
    view.backgroundColor = UIColor.systemGreen
    james.backgroundColor = UIColor.systemBlue
    james.isUserInteractionEnabled = true
    [james].forEach({
          $0.translatesAutoresizingMaskIntoConstraints = false
          self.view.addSubview($0)

      })
    NSLayoutConstraint.activate ([
               james.widthAnchor.constraint(equalToConstant: 200),
               james.heightAnchor.constraint(equalToConstant: 200),
    ])
    james.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.panGestureAction(_:))))
}


}
...