【问题标题】:Cropping part of UIImage with the screen aspect ratio使用屏幕纵横比裁剪部分 UIImage
【发布时间】:2018-01-25 16:07:45
【问题描述】:

我已经为此苦苦挣扎了一段时间。当您选择壁纸时,我想制作类似于 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 矩形,这也是我想从原始图像中裁剪的区域。非常感谢任何能让我摆脱痛苦的想法!

【问题讨论】:

    标签: ios swift uiscrollview uiimage crop


    【解决方案1】:

    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()
    
    }
    

    【讨论】:

    • 这很好用,但我也有屏幕上的按钮,即使我通过 isHidden 属性隐藏它们也是如此。
    • 隐藏你不想成为屏幕截图一部分的东西@MHCsk
    • 我在代码之前调用了 self.cropButton.isHidden = true,但按钮在快照上仍然可见。
    • 太棒了!我也弄乱了 DispatchQueue,但我不知道 asyncAfter 方法。它工作完美。谢谢你的传奇!
    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    相关资源
    最近更新 更多