churabou / iOS-develop-blog

0 stars 0 forks source link

5月1日(火) マスク画像を作成した。 #17

Open churabou opened 6 years ago

churabou commented 6 years ago
CIGaussianGradientではいた CoreGraphicsで描いた

CIGaussianGradient使ってみたやつ

    func gaussianGradient() -> CIImage {
        let filter = CIFilter(name: "CIGaussianGradient")!
        filter.setValue(CIVector(x: 300, y: 300), forKey: "inputCenter")
        filter.setValue(CIColor.white, forKey: "inputColor0")
        filter.setValue(CIColor.black, forKey: "inputColor1")
        filter.setValue(150, forKey: "inputRadius")
        let output = filter.outputImage!

        let cropFilter = CIFilter(name: "CICrop")!
        cropFilter.setValue(output, forKey: "inputImage")
        cropFilter.setValue(CGRect(origin: .zero, size: .equal(to: 600)), forKey: "inputRectangle")
        return cropFilter.outputImage!
    }
        let ciImage = gaussianGradient()
        let context = CIContext()
        let cgImage = context.createCGImage(ciImage, from: ciImage.extent)

        let layer = CALayer()
        layer.bounds.size = .equal(to: 300)
        layer.position = view.center
        layer.contents = cgImage!
        view.layer.addSublayer(layer)

coreGraphicsを使って描いてみたやつ


class RadialGradientLayer: CAShapeLayer {

    required override init() {
        super.init()
        needsDisplayOnBoundsChange = true
        fillRule = kCAFillRuleEvenOdd
        fillColor = UIColor.black.cgColor
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    required override init(layer: Any) {
        super.init(layer: layer)
    }

    public var colors = [UIColor.clear.cgColor, UIColor.black.cgColor]

    override func draw(in ctx: CGContext) {
        ctx.saveGState()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let locations: [CGFloat] = [0, 1]

        let gradient = CGGradient(colorsSpace: colorSpace,
                                  colors: colors as CFArray,
                                  locations: locations)

        let center = bounds.center
        let radius = min(bounds.width, bounds.height) / 4
        ctx.drawRadialGradient(gradient!,
                               startCenter: center,
                               startRadius: 0.0,
                               endCenter: center,
                               endRadius: radius+1, //切れ目が見えたので
                               options: .drawsBeforeStartLocation)

        let path = UIBezierPath(rect: bounds)
        path.append(UIBezierPath(arcCenter: center,
                                 radius: radius,
                                 startAngle: 0,
                                 endAngle: 2*CGFloat.pi,
                                 clockwise: true))

        self.path = path.cgPath
    }
}
        let layer = RadialGradientLayer()
        layer.bounds.size = .equal(to: 300)
        layer.position = view.center
        view.layer.addSublayer(layer)