【发布时间】: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