使用 CGImageRef 裁剪图像

Crop Image with CGImageRef

我正在使用核心图形绘制图像,但我想将其用作另一幅图像的蒙版,但只是得到清晰的矩形图像。

看看我的裁剪功能有什么问题?

    UIGraphicsBeginImageContext(CGSizeMake(self.bounds.size.width / 0.5, self.bounds.size.height / 0.5))
    let imageCtx = UIGraphicsGetCurrentContext()
    CGContextAddArc(imageCtx, CGFloat(self.frame.size.width )  , CGFloat(self.frame.size.height ), 158, 0, CGFloat(DegreesToRadians(Double(angle))) , 0)
    CGContextSetLineWidth(imageCtx, 80)
    CGContextDrawPath(imageCtx, .Stroke)
    let myMask :CGImageRef = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext())!

    UIGraphicsEndImageContext()
    let maskImage = UIImage(CGImage: myMask)

    let testVideoPreview = UIImage(named: "alex")
    guard let makedImage = testVideoPreview else {return}

    var imageMaskOne: CGImageRef = CGImageMaskCreate(CGImageGetWidth(myMask), CGImageGetHeight(myMask), CGImageGetBitsPerComponent(myMask), CGImageGetBitsPerPixel(myMask), CGImageGetBytesPerRow(myMask), CGImageGetDataProvider(myMask), nil,     // Decode is null
        true)!

    let masked: CGImageRef = CGImageCreateWithMask(makedImage.CGImage, imageMaskOne)!

    //Finished
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 350, height: 350))
    imageView.image = UIImage(CGImage: masked)
    self.addSubview(imageView)

如果您只需要在特定坐标处创建裁剪,则有更简单的方法CGImageCreateWithImageInRect

func CGImageCreateWithImageInRect(_ image: CGImage?, _ rect: CGRect) -> CGImage?

这里是documentation.