簡體   English   中英

使用屏幕長寬比裁剪UIImage的一部分

[英]Cropping part of UIImage with the screen aspect ratio

我已經為此苦苦掙扎了一段時間了。 當您選擇牆紙時,我想使圖像裁剪器類似於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矩形,該矩形代表向用戶顯示的區域,這也是我要從原始圖像中裁剪的區域。 非常感謝任何使我擺脫困境的想法!

snapshotImageFromMyView是輸出圖像

self.btn.isHidden = true

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        UIGraphicsBeginImageContextWithOptions(self.YourView.bounds.size, self.YourView.isOpaque, 0.0)
        self.YourView.drawHierarchy(in: self.YourView.bounds, afterScreenUpdates: false)
    let snapshotImageFromMyView = UIGraphicsGetImageFromCurrentImageContext()
     UIGraphicsEndImageContext()

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM