我想将CIFilter应用于CAShapeLayer.filters。 这是正确的假设如何做到这一点:
要从CAShapeLayer创建CGImage,我使用了CAShapeLayer.contents,但在我的情况下,内容是nil,如果我将CAShapeLayer渲染到图像上下文,我也无法获得图像。
override func layoutSubviews()
{
if(self.shapeLayer == nil && self.path != nil && self.pathOriginationSize != CGSizeZero)
{
let scaleFactor = self.scaleFactor(self.pathOriginationSize, targetSize: self.bounds.size)
_scaledPath = UIBezierPath(CGPath: self.path.CGPath)
_scaledPath.lineWidth = self.path.lineWidth
_scaledPath.applyTransform(CGAffineTransformMakeScale(scaleFactor.x, scaleFactor.y))
_scaledPath.lineCapStyle = CGLineCap.Round
self.shapeLayer = CAShapeLayer()
self.shapeLayer.path = _scaledPath.CGPath
self.shapeLayer.strokeColor = UIColor.blackColor().CGColor
self.shapeLayer.lineWidth = self.path.lineWidth
let imageSize = CGPathGetBoundingBox(_scaledPath.CGPath).size
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
self.shapeLayer.renderInContext(context!)
_ = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let cgImage = self.shapeLayer.contents as! CGImageRef
let inputImage = CIImage(CGImage: cgImage)
let blurFilter = CIFilter(name: "CIZoomBlur")
blurFilter?.setValue(inputImage, forKey: kCIInputImageKey)
blurFilter?.setDefaults()
self.shapeLayer.filters = [blurFilter!]
self.shapeLayer.shouldRasterize = true
self.layer.addSublayer(self.shapeLayer)
}
}
答案 0 :(得分:0)
CALayer.filters
。
在这种情况下无需使用CAShapeLayer
(因为您无法使用filters
)。您只需从CGImage
创建UIBezierPath
(就像您正在做的那样;只需stroke
和/或fill
路径,而不是调用renderInContext
)。然后使用apply
CIFilter
到结果,创建CGImage
并将其分配给contents
。 (从上面的代码中,你似乎明白了如何做所有这些事情,所以我不会在这里写出来。)