我正在用我的应用程序中的相机拍照。如图所示,我在图像视图的顶部有一个透明孔层
我想要做的是在该圆孔中裁剪图像。我正在使用该代码,但无法正常工作
UIGraphicsBeginImageContextWithOptions(CGSize(width: radius-60, height: radius-60),false,0)
final!.draw(at: CGPoint(x: 30, y: screenHeight/2 - radius/2 + 30)
let tmpImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
其中UIGraphicsBeginImageContextWithOptions中的高度和宽度是圆形孔的高度和宽度,而绘制中的x和y是孔的x坐标,而y坐标是孔的上边界
图片代码
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("here123")
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.contentMode = .scaleAspectFit
imageView.image = image
self.view.backgroundColor = UIColor.black
picker.dismiss(animated: true, completion: nil)
photoSave()
}
透明孔的代码
screenWidth = self.view.frame.width
screenHeight = self.view.frame.height
radius = min(screenWidth,screenHeight)
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), cornerRadius: 0)
let circlePath = UIBezierPath(roundedRect: CGRect(x: 30, y: screenHeight/2 - radius/2 + 30 , width: radius-60, height: radius - 60), cornerRadius: radius/2 - 30)
path.append(circlePath)
path.usesEvenOddFillRule = true
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.black.cgColor
fillLayer.opacity = 0.5
view.layer.addSublayer(fillLayer)
答案 0 :(得分:1)
您可以使用它来舍入UIImage:
func roundedImage(from image: UIImage, radius: CGFloat) -> UIImage {
let frame = CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius)
let imageView: UIImageView = UIImageView(frame: frame)
imageView.image = image
let layer = imageView.layer
layer.masksToBounds = true
layer.cornerRadius = radius
UIGraphicsBeginImageContext(imageView.bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let roundedImg = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImg!
}
let img = UIImage(named: "NameOfTheImage")!
let r: CGFloat = 300
roundedImage(from: img, withRadius: r)
要在特定的圆圈中渲染图像,而不仅仅是使图像变圆,请使用以下命令:
UIGraphicsBeginImageContext(newImageView.bounds.size)
let frame = CGRect(x: 30, y: screenHeight/2 - radius/2 + 30, width: radius - 60, height: radius - 60)
guard let img = imageView.image, let cgImage = img.cgImage, let croppedCGImage = cgImage.cropping(to: frame) else {
fatalError("Couldn't crop the image")
}
let newImage = UIImage(cgImage: croppedCGImage)
let newImageView: UIImageView = UIImageView(image: newImage)
let layer = newImageView.layer
layer.masksToBounds = true
layer.cornerRadius = radius
layer.render(in: UIGraphicsGetCurrentContext()!)
guard let roundedImg = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("Couldn't render the image")
}
UIGraphicsEndImageContext()
// use roundedImg