将UIImage剪切到UIBezierPath(不屏蔽) [英] Clip UIImage to UIBezierPath (not masking)
问题描述
我正在尝试基于给定的UIBezierPath
裁剪UIImage
,但是生成的图像保留了原始形状和大小.我希望形状和大小类似于路径,即新图像的可见内容.
I'm trying to clip a UIImage
based on a given UIBezierPath
, but the resulting image retains the original shape and size. I want the shape and size to resemble the path, i.e. the visible content of the new image.
看看下面的例子:
以下是我用来屏蔽给定路径的图像的代码:
The following is the code I am using to mask an image given a path:
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
}
一种解决方案是在蒙版后裁剪图像,但理想情况下,我希望一次完成尽可能简单有效的操作.
One solution would be to crop the image after masking it, but ideally I want this to be done as simple and efficiently as possible in one go.
任何解决方案/技巧都将不胜感激.
Any solution/ tips would be appreciated.
推荐答案
感谢 Rob 我能够实现一个解决方案使用CGImage
的cropping(to:)
方法.
Thanks to Rob I was able to implement a solution using the cropping(to:)
method of CGImage
.
这是一个分为两个步骤的过程,首先我使用给定的路径遮罩图像,然后使用路径的边界裁剪结果.
This is a two step process where first I mask the image using the given path, and then crop the result using the bounds of the path.
以下是用于实现剪切 UIBezierPath
UIImage
扩展名的最终工作源代码:
The following is my final working source code for implementing a clipping UIBezierPath
UIImage
extension:
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
}
}
这篇关于将UIImage剪切到UIBezierPath(不屏蔽)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!