使用屏幕宽高比裁剪UIImage的一部分

时间:2017-08-17 09:47:15

标签: ios swift uiscrollview uiimage crop

我一直在努力解决这个问题已有一段时间了。当您选择壁纸时,我想使图像裁剪器与iOS中包含的图像裁剪器类似。基本上我希望用户从图像中选择的区域具有屏幕的缩放和纵横比(因此用户可以稍后将图像用作壁纸)。像这样:

https://gfycat.com/TornMaleAlligatorsnappingturtle

我已经设法用UIScrollView和UIImageView创建接口:

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

var scrollView: UIScrollView!
var imageView: UIImageView!

var croppedImage: UIImage?

@IBOutlet weak var cropButton: UIButton! {
    didSet{
        cropButton.backgroundColor = UIColor.gray
    }
}


override func viewDidLoad() {

    super.viewDidLoad()

    let image = UIImage(named: "mountains")!

    imageView = UIImageView(image: image)
    imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size:image.size)
    imageView.contentMode = .scaleAspectFill

    scrollView = UIScrollView(frame: view.bounds)
    scrollView.backgroundColor = UIColor.black
    scrollView.contentSize = imageView.bounds.size

    scrollView.delegate = self

    setZoomScale()
    //centerScrollViewContents()

    scrollView.addSubview(imageView)
    view.addSubview(scrollView)
    view.bringSubview(toFront: cropButton)

}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
}

@IBAction func crop(_ sender: UIButton) {

    let rect = CGRect(x: ?, y: ?, width: ?, height: ?)
    let croppedCGImage = imageView.image?.cgImage?.cropping(to: rect)
    self.croppedImage = UIImage(cgImage: croppedCGImage!)
}

func setZoomScale() {
    let imageViewSize = imageView.bounds.size
    let scrollViewSize = scrollView.bounds.size
    //let widthScale = scrollViewSize.width / imageViewSize.width
    let heightScale = scrollViewSize.height / imageViewSize.height

    scrollView.minimumZoomScale = heightScale //min(widthScale, heightScale)
    scrollView.maximumZoomScale = 3
    scrollView.zoomScale = heightScale

    print(heightScale) 
} 
}.

我可以缩放和平移图像没问题。问题是我不知道如何创建表示向用户显示的区域的CGRect矩形,该区域也是我想从原始图像中裁剪的区域。任何让我摆脱痛苦的想法都非常感谢!

1 个答案:

答案 0 :(得分:3)

snapshotImageFromMyView是输出图像

    1.go to this url  https://packagecontrol.io/installation copy the code of sublime text 3 or sublime text 2 from the url

    2.open sublime text editor and go to menu options of View and select the "show console" 

    3.then paste the code from the above url and press enter.It will install the package manager.

    4.press ctrl+shift+p and type install in the input box. A list of options will come,then select the Install package option.It will install.

    5.After installing the above press again ctrl+shift+p and type the "babel" and select babel in the list.It will install the babel syntax

    6.to change the syntax of the page select the view menu and choose syntax/babel