https://www.raywenderlich.com/2305-core-image-tutorial-getting-started
希望它有所帮助。设计故事板并在ViewController类中创建出口和属性。
let picker = UIImagePickerController()
var circlePath = UIBezierPath()
@IBOutlet weak var crop: CropView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scroll: UIScrollView!
func point(inside point: CGPoint, with event: UIEvent?) -> Bool{
return false
}
picker.sourceType = .photoLibrary
present(picker, animated: true, completion: nil)
并将UIImagePickerControllerDelegate添加为类的子类型。在viewDidLoad中,
picker.delegate = self
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = chosenImage.resizeImage()
dismiss(animated:true, completion: nil)
如果您要在取消时关闭照片相册,请使用imagePickerControllerDidCancel委托。
从相机拍摄照片 - 创建IBAction以从相机拍摄图像。首先,检查设备中是否可用SourceTypeAvailable。如果设置了拾取器相机捕获模式为照片。否则处理该操作。然后将源类型设置为相机,相机捕获模式设置为照片。
if UIImagePickerController.isSourceTypeAvailable(.camera){
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.photo
picker.modalPresentationStyle = .custom
present(picker,animated: true,completion: nil)
}else{
//action performed if there is no camera in device.
}
裁剪 —
将子图层添加到选定的图像中 - 此图层提供了一个区域来修复裁剪框。
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height), cornerRadius: 0)
将路径分配给类型为UIBezierPath的圆形路径属性。使用BezierPath,您可以将裁剪框架更改为不同的形状。
circlePath = UIBezierPath(roundedRect: CGRect(x: (self.view.frame.size.width / 2) - (size/2), y: (self.view.frame.size.height / 2) - (size / 2), width: size, height: size, cornerRadius: 0)
path.append(circlePath)
在其坐标空间中绘制立方贝塞尔样条的CAShapeLayer。
let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
view.layer.addSublayer(fillLayer)
let factor = imageView.image!.size.width/view.frame.width
用滚轮缩放来进行缩放,zoomScale。
let scale = 1/scroll.zoomScale
然后设置裁剪区域框架(x,y,宽度,高度)。
let x = (scroll.contentOffset.x + circlePath.bounds.origin.x - imageFrame.origin.x) * scale * factor
let y = (scroll.contentOffset.y + circlePath.bounds.origin.y - imageFrame.origin.y) * scale * factor
let width = circlePath.bounds.width * scale * factor
let height = circlePath.bounds.height * scale * factor
let croppedCGImage = imageView.image?.cgImage?.cropping(to: croparea)
let croppedImage = UIImage(cgImage: croppedCGImage!)