带有CIFilters的CAShapeLayer

时间:2015-10-28 06:29:28

标签: ios swift uiimage cashapelayer cifilter

我想将CIFilter应用于CAShapeLayer.filters。 这是正确的假设如何做到这一点:

  • 创建CAShapeLayer
  • 从CAShapeLayer创建CGImage或UIImage
  • 使用CGImage或UIImage创建CIFilter
  • 将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)
        }
    }

1 个答案:

答案 0 :(得分:0)

iOS上未实现

CALayer.filters

在这种情况下无需使用CAShapeLayer(因为您无法使用filters)。您只需从CGImage创建UIBezierPath(就像您正在做的那样;只需stroke和/或fill路径,而不是调用renderInContext)。然后使用apply CIFilter到结果,创建CGImage并将其分配给contents。 (从上面的代码中,你似乎明白了如何做所有这些事情,所以我不会在这里写出来。)