ios - 将 UIImage 剪辑到 UIBezierPath(不屏蔽)

标签 ios swift uiimage uibezierpath uigraphicscontext

我正在尝试根据给定的 UIBezierPath 裁剪 UIImage,但生成的图像保留了原始形状和大小。我希望形状和大小类似于路径,即新图像的可见内容。

看看下面这个例子:

Input image, input path, actual result, and desired result

以下是我用来屏蔽给定路径的图像的代码:

func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(CGSize(
        width: size.width,
        height: size.height
    ), false, 0.0)
    let context = UIGraphicsGetCurrentContext()!
    context.saveGState()

    path.addClip()
    draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()!

    context.restoreGState()
    UIGraphicsEndImageContext()

    return newImage
}

一种解决方案是在蒙版后裁剪图像,但理想情况下,我希望一次性尽可能简单高效地完成此操作。

任何解决方案/提示将不胜感激。

最佳答案

感谢Rob我能够使用 CGImagecropping(to:) 方法实现解决方案。

这是一个两步过程,首先我使用给定的路径遮盖图像,然后使用路径的边界裁剪结果。

以下是我实现剪辑 UIBezierPath UIImage 扩展的最终工作源代码:

extension UIImage {

    func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage {
        // Mask image using path
        let maskedImage = imageByApplyingMaskingBezierPath(path)

        // Crop image to frame of path
        let croppedImage = UIImage(cgImage: maskedImage.cgImage!.cropping(to: path.bounds)!)
        return croppedImage
    }

    func imageByApplyingMaskingBezierPath(_ path: UIBezierPath) -> UIImage {
        // Define graphic context (canvas) to paint on
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()!
        context.saveGState()

        // Set the clipping mask
        path.addClip()
        draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        let maskedImage = UIGraphicsGetImageFromCurrentImageContext()!

        // Restore previous drawing context
        context.restoreGState()
        UIGraphicsEndImageContext()

        return maskedImage
    }

}

关于ios - 将 UIImage 剪辑到 UIBezierPath(不屏蔽),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815247/

相关文章:

iphone - 将 NSMutableArray 保存到 NSUserDefaults - 添加对象时出现问题

ios - 无法推断通用参数 - 数组扩展

ios - 图像未通过 IOS 中的 POST 方法发送到 PHP Web 服务

iOS 图表 - 如何设置 x 轴下的 y 值

json - 使用 Swifty JSON 响应填写字典?

ios - 将 AVPlayerItem 转换为 NSData

iphone - -[NSConcreteMutableData _isResizable] : issue with UIImage

iOS Swift 3 performSelector onMainThread

c# - Xamarin.Forms 中的 IOS 联系人邮政地址

ios - 访问另一个类中的 ScrollView 委托(delegate)方法