0
我一直在爲此奮鬥了很長一段時間。當你選擇你的壁紙時,我想讓圖像裁剪器與iOS中包含的圖像裁剪器類似。基本上我希望用戶從屏幕上縮放和縱橫比的圖像中裁剪的區域(以便用戶以後可以將圖像用作牆紙)。就像這樣:用屏幕縱橫比裁剪UIImage的一部分
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矩形來表示向用戶顯示的區域,這也是我想從原始圖像裁剪的區域。任何想法將讓我擺脫我的苦難,非常感謝!
這工作得很好,但我有得到藏漢快照屏幕上的按鈕,即使我通過是否隱藏屬性隱藏起來。 – MHCsk
隱藏你不想成爲屏幕截圖的一部分@MHCsk –
我在代碼之前調用self.cropButton.isHidden = true,但該按鈕在快照上仍然可見。 – MHCsk