在Swift中对CIFilter进行子类化

时间:2014-08-29 16:56:03

标签: ios swift cifilter

我试图创建CIFilter的子类,如下所示:

class ColorMonochromeFilter: CIFilter {

    required init(red: CGFloat!, green: CGFloat!, blue: CGFloat!) {

        super.init(name: "ColorMonochrome")
        setDefaults()

        let colour = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        setValue(colour, forKey: kCIInputColorKey)
    }
}

我收到以下错误消息:

  1. Class' ColorMonochromeFilter'没有实现它的超类 必要成员
  2. 必须调用指定的初始化程序 超类' CIFilter'
  3. 由于init(coder aDecoder: NSCoder!)符合CIFilter协议而不是NSCoding,因此指定的初始化程序为init(name: String!),而CIFilter required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } 的扩展名中声明

    我可以通过添加以下内容删除第一个错误:

    @implementation ASHColorMonochromeFilter
    
        + (ASHColorMonochromeFilter *) filterWithRed: (CGFloat) red green:(CGFloat)green blue:(CGFloat)blue
        {
            ASHColorMonochromeFilter * filter = (ASHColorMonochromeFilter *)[ASHColorMonochromeFilter filterWithName: @"CIColorMonochrome"];
    
            UIColor * color = [UIColor colorWithRed: red green: green blue: blue alpha: 1.0];
            [filter setValue: color forKey: kCIImageColorSpace];
    
            return filter;
        }
    

    (虽然这看起来有点多余!)

    有没有办法解决第二个问题?


    我在这里想要实现的是Swift等同于此:

    {{1}}

1 个答案:

答案 0 :(得分:4)

您的Objective-C类方法

+ (ASHColorMonochromeFilter *) filterWithRed: (CGFloat) red green:(CGFloat)green blue:(CGFloat)blue

实际上返回CIFilter的(子类)实例。同样可以实现 在Swift中使用便利初始化程序

extension CIFilter {
     convenience init(red: CGFloat, green: CGFloat, blue: CGFloat) {
        self.init(name:"CIColorMonochrome")
        setDefaults()
        let colour = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        setValue(colour, forKey: kCIInputColorKey)
    }
}

被称为

let filter = CIFilter(red: 0.1, green: 0.2, blue: 0.3)