如何使用 swift 在圆孔中裁剪缩放图像

How to crop a zoomed Image in a circular hole with swift

我正在用我的应用程序拍照。如图所示,我在图像视图顶部有一个带有透明孔的层

我想做的是在那个圆孔中裁剪图像。我正在使用该代码,但它不起作用

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中的高和宽为圆孔的高和宽,draw中的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)

您可以使用它来舍入 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